Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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

like image 697
Eric Herlitz Avatar asked Mar 24 '13 15:03

Eric Herlitz


4 Answers

Yes, Twig supports regular expressions in comparisons: http://twig.sensiolabs.org/doc/templates.html#comparisons

In your case it would be:

{% if item.ContentTypeId matches '/^0x0120.*/' %}
  ...
{% else %}
  ...
{% endif %}
like image 22
Marek Avatar answered Nov 10 '22 00:11

Marek


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

like image 100
benske Avatar answered Nov 10 '22 01:11

benske


You can just use the slice filter. Simply do:

{% if item.ContentTypeId[:6] == '0x0120' %}
{% endif %}
like image 8
Prisoner Avatar answered Nov 10 '22 00:11

Prisoner


You can always make your own filter that performs the necessary comparison.

As per the docs:

When called by Twig, the PHP callable receives the left side of the filter (before the pipe |) as the first argument and the extra arguments passed to the filter (within parentheses ()) as extra arguments.

So here is a modified example.

Creating a filter is as simple as associating a name with a PHP callable:

// an anonymous function
$filter = new Twig_SimpleFilter('compareBeginning', function ($longString, $startsWith) {
    /* do your work here */
});

Then, add the filter to your Twig environment:

$twig = new Twig_Environment($loader);
$twig->addFilter($filter);

And here is how to use it in a template:

{% if item.ContentTypeId | compareBeginning('0x0120') == true %}
{# not sure of the precedence of | and == above, may need parentheses #}

I'm not a PHP guy, so I don't know how PHP does regexes, but the anonymous function above is designed to return true if $longString begins with $startsWith. I'm sure you'll find that trivial to implement.

like image 1
ladaghini Avatar answered Nov 10 '22 01:11

ladaghini