“Begins with” in Twig template

后端 未结 4 1328
半阙折子戏
半阙折子戏 2021-02-05 01:35

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

{% if item.ContentTypeId == \'0x0120\' %}
    

        
相关标签:
4条回答
  • 2021-02-05 01:57

    You can just use the slice filter. Simply do:

    {% if item.ContentTypeId[:6] == '0x0120' %}
    {% endif %}
    
    0 讨论(0)
  • 2021-02-05 01:59

    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 %}
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-05 02:09

    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.

    0 讨论(0)
提交回复
热议问题