symfony 2 twig limit the length of the text and put three dots

前端 未结 13 2028
太阳男子
太阳男子 2021-01-30 00:36

How can I limit the length of the text, e.g., 50, and put three dots in the display?

{% if myentity.text|length > 50 %}

{% block td_text %} {{ myentity.text}         


        
13条回答
  •  孤街浪徒
    2021-01-30 01:01

    @mshobnr / @olegkhuss solution made into a simple macro:

    {% macro trunc(txt, len) -%}
        {{ txt|length > len ? txt|slice(0, len) ~ '…' : txt }}
    {%- endmacro %}
    

    Usage example:

    {{ tools.trunc('This is the text to truncate. ', 50) }}
    

    N.b. I import a Twig template containing macros and import it as 'tools' like this (Symfony):

    {% import "@AppBundle/tools.html.twig" as tools -%}
    

    Also, I replaced the html character code with the actual character, this should be no problem when using UTF-8 as the file encoding. This way you don't have to use |raw (as it could cause a security issue).

提交回复
热议问题