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

前端 未结 13 2025
太阳男子
太阳男子 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:09

    Update for Twig 2 and Twig 3.

    truncate filter is not available, instead of it you may use u-filter

    here is an example:

    {{ 'Lorem ipsum'|u.truncate(8) }}
    Lorem ip
    
    {{ 'Lorem ipsum'|u.truncate(8, '...') }}
    Lorem...
    

    Note: this filter is part of StringExtension that can be required by

    twig/string-extra
    
    0 讨论(0)
  • 2021-01-30 01:10

    @olegkhuss solution with named UTF-8 Elipsis: {{ (my.text|length > 50 ? my.text|slice(0, 50) ~ '…' : my.text) }}

    0 讨论(0)
  • 2021-01-30 01:11

    Another one is:

    {{ myentity.text[:50] ~ '...' }}
    
    0 讨论(0)
  • 2021-01-30 01:17

    I know this is a very old question, but from twig 1.6 you can use the slice filter;

    {{ myentity.text|slice(0, 50) ~ '...' }}
    

    The second part from the tilde is optional for if you want to add something for example the ellipsis.

    Edit: My bad, I see the most up-voted answer do make use of the slice filter.

    0 讨论(0)
  • 2021-01-30 01:18
    {{ myentity.text|length > 50 ? myentity.text|slice(0, 50) ~ '...' : myentity.text  }}
    

    You need Twig 1.6

    0 讨论(0)
  • 2021-01-30 01:19

    why not use twig's truncate or wordwrap filter? It belongs to twig extensions and lib is part of Symfony2.0 as i see.

    {{ text|truncate(50) }}
    
    0 讨论(0)
提交回复
热议问题