限制字符串树枝

问题描述 投票:9回答:6

如何限制字符串长度?我从我的数据库中获取了描述值,但我只想显示一些特定的字符。

  • 如何在我的树枝模板中执行此操作?
  • 在我的控制器中做它更好吗?
templates symfony twig
6个回答
10
投票

尝试使用Truncate功能:

首先,您需要激活文本扩展名:

# app/config/config.yml
  services:
    twig.extension.text:
        class: Twig_Extensions_Extension_Text
        tags:
            - { name: twig.extension }

然后,您可以在Twig模板中调用truncate() helper,如下所示:

{{ variable.description | truncate(100, true) }}

22
投票

试试这个 :

{{ entity.description|striptags|slice(0, 40) }}
  1. striptags filter将删除HTML标签,这将避免在2中剪切标签,例如此基本情况:Text ... <img src="http://examp
  2. slice filter将剪切文本,仅保留40个第一个字符

9
投票

我用它来截断博客文章并显示省略号..

{{ post.excerpt|striptags|length > 100 ? post.excerpt|striptags|slice(0, 100) ~ '...' : post.excerpt|striptags }}

如果帖子摘录长度大于100个字符,那么slice它是从第一个开始的100s字符并附加一个'...'否则显示全文..


1
投票

所以上面列出的几个选项没有给出任何细节,所以这里有更多信息:

{{ variable.description|truncate(100) }}

这样可以将文本剪切为100个字符。这里的问题是,如果第100个字符位于单词的中间,那么该单词将被切成两半。

所以要解决这个问题,我们可以在truncate调用中添加'true':

{{ variable.description|truncate(100, true) }}

当我们这样做时,truncate将检查我们是否在截止点的一个单词的中间,如果是,它将在该单词的末尾剪切字符串。

如果我们还希望截断可能包含某些HTML的字符串,我们需要先删除这些标记:

{{ (variable.description|striptags)|truncate(100) }}

唯一的缺点是我们将丢失任何换行符(例如内置于段落标记中的那些)。如果你要截断一个相对较短的字符串,这可能不是问题。


0
投票

我知道这不是你特定问题的答案,因为你想截断到一定数量的字符,但使用CSS也可以实现类似的东西。除非你仍然支持IE8和IE9,否则有一些警告。

使用文本溢出,可以使用省略号值来完成。以下是CSS-TRICKS的示例:

.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

这将允许您将文本截断为容器宽度,但是,对于特定字符计数,TRUNCATE函数接受的TWIG分辨率完美地工作。

参考:https://css-tricks.com/snippets/css/truncate-string-with-ellipsis/


0
投票

你可以使用这个Twig扩展:

用法

{{ text|ellipsis(20) }}
{{ text|ellipsis(20, '///') }}

namespace AppBundle\Twig;

//src/AppBundle/Twig/TwigTextExtension.php
class TwigTextExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('ellipsis', array($this, 'ellipsisFilter')),
        );
    }

    public function ellipsisFilter($text, $maxLen = 50, $ellipsis = '...')
    {
        if ( strlen($text) <= $maxLen)
            return $text;
        return substr($text, 0, $maxLen-3).$ellipsis;

    }
}

将其注册为services.yml中的服务

services:
    twig.extension.twigtext:
        class: AppBundle\Twig\TwigTextExtension
        tags:
            - { name: twig.extension }
© www.soinside.com 2019 - 2024. All rights reserved.