"Begins with" in Twig template

Eric Herlitz picture Eric Herlitz · Mar 24, 2013 · Viewed 32k times · Source

I have a twig template where I would like to test if an item begins with a certain value

{% if item.ContentTypeId == '0x0120' %}
    <td><a href='?parentId={{ item.Id }}'>{{ item.BaseName }}</a><br /></td>
{% else %}
    <td><a href='?{{ item.UrlPrefix }}'>{{ item.LinkFilename }}</a></td>
{% endif %}

The 0x0120 can look like that or be more complex like this 0x0120D52000D430D2B0D8DD6F4BBB16123680E4F78700654036413B65C740B168E780DA0FB4BX. The only thing I want to do is to ensure that it starts with the 0x0120.

The ideal solution would be to solve this by using regex but I'm not aware if Twig supports this?

Thanks

Answer

benske picture benske · May 15, 2014

You can do that directly in Twig now:

{% if 'World' starts with 'F' %}
{% endif %}

"Ends with" is also supported:

{% if 'Hello' ends with 'n' %}
{% endif %}

Other handy keywords also exist:

Complex string comparisons:

{% if phone matches '{^[\\d\\.]+$}' %} {% endif %}

(Note: double backslashes are converted to one backslash by twig)

String contains:

{{ 'cd' in 'abcde' }}
{{ 1 in [1, 2, 3] }}

See more information here: http://twig.sensiolabs.org/doc/templates.html#comparisons