149

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}}{% endblock %}

{%endif%}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
GRafoKI
  • 1,515
  • 2
  • 9
  • 8
  • 4
    The "three dots" is actually a single character called an Ellipsis. This is three full stops `...` and this is an Ellipsis `…` – Luke Cousins May 18 '17 at 14:50

16 Answers16

232
{{ myentity.text|length > 50 ? myentity.text|slice(0, 50) ~ '...' : myentity.text  }}

You need Twig 1.6

olegkhuss
  • 3,762
  • 2
  • 17
  • 7
127

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) }}
mrMantir
  • 2,285
  • 1
  • 17
  • 20
  • 6
    I'm using Symfony 2.3 and the truncate filter is not part of the default extensions. Therefore, I resorted to Manuel's solution instead. – maurits Oct 14 '13 at 16:48
  • 8
    To enable the extension in Symfony add this to one of your configuration files: https://gist.github.com/pschultz/f33bfff72692ca0b6916 – Peter Jun 27 '14 at 15:00
  • 1
    To append `...`, the second parameter should be set to `true` such as `{{ text|truncate(50, true)` – Sithu May 12 '17 at 15:16
  • Actually setting the second parameter to true would make it preserve whole words. It adds the ellipses by default. The third parameter can change the ellipses to anything you want. http://twig-extensions.readthedocs.io/en/latest/text.html#truncating-text – beta Aug 10 '17 at 16:08
  • 1
    Using Symfony 2.8, I had to install this extension to use it. ```require twig/extensions``` – beta Aug 10 '17 at 16:10
37

Another one is:

{{ myentity.text[:50] ~ '...' }}
Manuel Bitto
  • 5,073
  • 6
  • 39
  • 47
21

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.

14

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

Matthias
  • 1,130
  • 10
  • 8
12

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
Danil Pyatnitsev
  • 2,172
  • 2
  • 26
  • 39
10

@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).

Graftak
  • 691
  • 7
  • 16
6

An even more elegant solution is to limit the text by the number of words (and not by number of characters). This prevents ugly tear throughs (e.g. 'Stackov...').

Here's an example where I shorten 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 %}
Julius B.
  • 191
  • 2
  • 3
6

Use the truncate filter to cut off a string after limit is reached

{{ "Hello World!"|truncate(5) }} // default separator is ...

Hello...

You can also tell truncate to preserve whole words by setting the second parameter to true. If the last Word is on the the separator, truncate will print out the whole Word.

 {{ "Hello World!"|truncate(7, true) }} // preserve words

Here Hello World!

If you want to change the separator, just set the third parameter to your desired separator.

{{ "Hello World!"|truncate(7, false, "??") }} 

Hello W??

goto
  • 7,908
  • 10
  • 48
  • 58
2

You can limit in following way. First is starting index and second is number of characters.

**{{ results['text'][4:2] }}**
Seymour
  • 7,043
  • 12
  • 44
  • 51
Zaheer Babar
  • 1,636
  • 1
  • 15
  • 17
1

if anyone needs this from the modern world, since this question is so old, I would do it this way: I would definitely not want to have an incomplete word at the end, therefor I prefer to do it with the following steps: limiting the wanted length of characters, exploid my text into a bunch of arrays of sentences separated with a comma or a dot depends on your text, remove the last array which represent the incomplete word then joining or imploiding those arrays together and of course do not forget to join them with that dot we removed when exploiding the string of characters, and outside of the twig {{}} add your three dots, with that been said it will look something like this:

{{myentity.text|slice(0,50)|split('.')|slice(0,-1)|join('.')}}...

<a href="#">readeMore</a>

Zache Leto
  • 31
  • 1
  • 2
1

u.truncate could be a modern option. An example from docs:

{{ 'Lorem ipsum dolor'|u.truncate(10, '...', false) }}
Lorem ipsum...

This solution requires string-extra:

composer require twig/string-extra
13DaGGeR
  • 147
  • 1
  • 10
0

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

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

Usage Example #1 (Output: "my long string here ..."):

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

Usage Example #2 (Output: "shorter string!"):

{{ _self.stringMaxLength("shorter string!", 20) }}
Ham L.
  • 465
  • 3
  • 4
0

Bugginess* in the new Drupal 8 capabilities here inspired us to write our own:

<a href="{{ view_node }}">{% if title|length > 32 %}{% set title_array = title|split(' ') %}{% set title_word_count = 0 %}{% for ta in title_array %}{% set word_count = ta|length %}{% if title_word_count < 32 %}{% set title_word_count = title_word_count + word_count %}{{ ta }} {% endif %}{% endfor %}...{% else %}{{ title }}{% endif %}</a>

This takes into consideration both words and characters (*the "word boundary" setting in D8 was displaying nothing).

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

In addition to Nemo64's comment under olegkhuss's response, I'd like to add that if you need to make the partial text to finishes on a word not a character, u can do this:

entity.text|split(' ', 11)|length > 10 ? entty.text|split(' ', 11)|slice(0, 10)|join(' ') ~ '…' : entity.text

In this example, all text with more than 10 words will be cuted after the 10th word.

Karobwe
  • 326
  • 2
  • 6
-1

It is better to use an HTML character

{{ entity.text[:50] }}&#8230;
Théo Attali
  • 2,200
  • 1
  • 9
  • 10
  • Can you add some explanation to your answer? Why should one use a HTML entity? And why do you append it to the text in each and every case, even if the text is less than 50 characters long? – Nico Haase Jan 09 '19 at 09:25
  • Hi, if you write three dots it's three separate dots but the "three dots" character is called an ellipsis. The ellipsis html entity is `…`. – Théo Attali Jan 09 '19 at 16:13
  • 1
    And why not use the unicode character for that ellipsis? – Nico Haase Jan 09 '19 at 16:14
  • You can use it too ! this comment was an answer to that comment https://stackoverflow.com/a/17118915/5923187 but that move was locked because of my reputation – Théo Attali Jan 09 '19 at 16:24