@ 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).
Graftak Apr 28 '17 at 9:39 on 2017-04-28 09:39
source share