Friday, April 2, 2021

Word truncate in Twig template

Follow the below code to achieve your word truncate in twig template:
It is done in a Drupal project so you can pick up the concept from here, not by doing copy paste code to achieve your result.

{% set field_description = view.style_plugin.getField(key'field_name')|render|striptags %}
{% set field_description_array = field_description|split(' ') %}
{% if field_description_array|length > 20 %}
    {% set word = 20 %}
    {% for i in range(1word) %}
        {{ field_description_array[i] }}
    {% endfor %}
    {{ '...' }}
{% else %}
    {% for key,value in field_description_array %}
        {{ value }}
    {% endfor %}
{% endif %}

Happy coding!

No comments:

Post a Comment

Change priority of dual boot OS

Change priority of dual boot OS  (Windows and Linux): Go to your Linux OS, install Grub customizer. Then change priority by up and down arro...