“Begins with” in Twig template

后端 未结 4 1339
半阙折子戏
半阙折子戏 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 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.

提交回复
热议问题