Search code examples
phpregextwigcomparison

"Begins with" in Twig template


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


Solution

  • Yes, Twig supports regular expressions in comparisons: https://twig.symfony.com/doc/3.x/templates.html#comparisons

    In your case it would be:

    {% if item.ContentTypeId matches '/^0x0120.*/' %}
      ...
    {% else %}
      ...
    {% endif %}