user2818060
user2818060

Reputation: 845

How To Limit The Length of Text in Twig

What i Need:

Here is what i have tried.

           {% set foo = item.Product_Name|split(',') %}
            {% for i in  foo|slice(0, 5) %}
            {{ i|length > 50 ? i|slice(0, 100) ~ ' ' : i  }}
                     {% if(loop.last)< 5 %}
                     ,
                    {% endif %}
            {% endfor %}

Upvotes: 1

Views: 5105

Answers (1)

qooplmao
qooplmao

Reputation: 17759

How about...

{% set names = item.Product_Name|split(',') %}
{% set maxNames = 4 %}

<ul>
    {% for name in names|slice(0, maxNames) %}
        <li>
            {{ name|length < 50 ? name : name|slice(0, 50) ~ '...' }}
        </li>
    {% else %}
        <li>No Results</li>
    {% endfor %}
    {% if names|length > maxNames %}
        <li>More Results Available</li>
    {% endif %}
</ul>

If not then I'm clearly not too sure about what you are actually after.

Also, what is the need for the ,'s in between each name?

If you are wanting something more complex then there is the possibility it should be handled outside of the template and in some kind of twig function.

Upvotes: 4

Related Questions