Symfony 2 twig limits text length and puts three dots

How can I limit the length of the text, for example 50, and put three dots on the display

{% if myentity.text|length > 50 %} {% block td_text %} {{ myentity.text}}{% endblock %} {%endif%} 
+83
symfony twig
30 Oct. '12 at 16:00
source share
9 answers
 {{ myentity.text|length > 50 ? myentity.text|slice(0, 50) ~ '...' : myentity.text }} 

You need twig 1.6

+134
Oct 30
source share

Why not use a thread trimmer or word filter? It refers to twig extensions and lib is part of Symfony2.0, as I see it.

 {{ text|truncate(50) }} 
+78
Oct 30
source share

Other:

 {{ myentity.text[:50] ~ '...' }} 
+38
Jun 15 '13 at 0:00
source share

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

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

The second part of the tilde is optional if you want to add something, such as an ellipsis.

Edit:. My bad one, I see that the most polled answer uses a cutoff filter.

+10
May 11 '16 at 9:15
source share

You can limit as follows. The index starts first, and the second the number of characters.

 **{{ results['text'][4:2] }}** 
+3
Dec 10 '14 at 13:50
source share

An even more elegant solution is to limit the text to the number of words (rather than the number of characters). This prevents ugly tears (for example, "Stackov ...").

Here is an example where I cut only text blocks longer than 10 words:

 {% set text = myentity.text |split(' ') %} {% if text|length > 10 %} {% for t in text|slice(0, 10) %} {{ t }} {% endfor %} ... {% else %} {{ text|join(' ') }} {% endif %} 
+3
Dec 01 '15 at 11:50
source share

@Olegkhuss solution called HTML Entity: {{ (my.text|length > 50 ? my.text|slice(0, 50) ~ '…' : my.text)|raw }}

+3
Dec 16 '16 at 14:24
source share

@ mshobnr / @ olegkhuss solution made in 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) }} 

Nb 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 not be a problem when using UTF-8 as the file encoding. This way you do not need to use |raw (as this may cause a security problem).

+3
Apr 28 '17 at 9:39 on
source share

I wrote this simple marco for the same purpose, hope this helps:

 {%- macro stringMaxLength(str, maxLength) -%} {%- if str | length < maxLength -%} {{ str }} {%- else -%} {{ str|slice(0, maxLength) }}... {%- endif -%} {%- endmacro -%} 

Usage example # 1 (output: "my long line is here ..."):

 {{ _self.stringMaxLength("my long string here bla bla bla la", 20) }} 

Example usage # 2 (output: "shorter line!"):

 {{ _self.stringMaxLength("shorter string!", 20) }} 
0
Sep 11 '15 at 5:47
source share



All Articles