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}
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) }}
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??
@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).
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 %}
It is better to use an HTML character
{{ entity.text[:50] }}…
You can limit in following way. First is starting index and second is number of characters.
**{{ results['text'][4:2] }}**