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

Wordpress debug log function

Wordpress error log code: if ( ! function_exists ( 'write_log' ) ) { function write_log ( $data ) { if ( defined ( '...