Blow string into array using Twig?

Is there any function to split the string into pieces based on the separator? The opposite of a filter join.

I mean something like explodein PHP. I need to check if the parameter contains the classgiven string:

{% macro nav_item(route, label, class, tooltip, placement) %}
{% spaceless %}
    {% if 'icon-white' in class|explode(' ') %}
    {% edif %}
{% endspaceless %}
{% endmacro %}
+5
source share
2 answers

Branch solution up to 1.10.3

AFAIK, in the branch there is no such filter.However, you can use the operator inas follows:

{% spaceless %}
    {% set test_class = ' ' ~ class ~ ' ' %}
    {% if ' icon-white ' in test_class %}
    {% endif %}
{% endspaceless %}

So, for example, if your class looks like 'some-class icon-white icon-white-2', then test_class will take a value ' some-class icon-white icon-white-2 'and inreturn truefor that class. He, however, will return falsefor ' some-class icon-white-2 ', as expected.

+1
source

As seen from Twig 1.10.3, there is a split filter.

{% set classes = class|split(' ') %}
+15
source

All Articles