Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode a string into array with Twig?

Tags:

twig

symfony

Is there any function for splitting a string into chunks based on a separator? The opposite of join filter.

I mean something like explode in PHP. I need to check if class parameter contains a given string:

{% macro nav_item(route, label, class, tooltip, placement) %}
{% spaceless %}
    {% if 'icon-white' in class|explode(' ') %}
    {% edif %}
{% endspaceless %}
{% endmacro %}
like image 440
Polmonino Avatar asked Mar 19 '12 00:03

Polmonino


2 Answers

As of Twig 1.10.3 there is the split filter.

{% set classes = class|split(' ') %}
like image 117
martinqt Avatar answered Nov 22 '22 23:11

martinqt


Solution for twig prior to 1.10.3

AFAIK, there is no such filter in twig. However you might use in operator as following:

{% 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 value of ' some-class icon-white icon-white-2 ' and in will return true for this class. It will, however, return false for ' some-class icon-white-2 ', as expected.

like image 31
Molecular Man Avatar answered Nov 23 '22 00:11

Molecular Man