Twig: in_array or similar possible within if statement?

后端 未结 6 677
终归单人心
终归单人心 2020-12-12 11:57

I am using Twig as templating engine and I am really loving it. However, now I have run in a situation which definitely mustbe accomplishable in a simpler way than I have fo

相关标签:
6条回答
  • 2020-12-12 12:12

    Just to clear some things up here. The answer that was accepted does not do the same as PHP in_array.

    To do the same as PHP in_array use following expression:

    {% if myVar in myArray %}
    

    If you want to negate this you should use this:

    {% if myVar not in myArray %}
    
    0 讨论(0)
  • 2020-12-12 12:20

    Try this

    {% if var in ['foo', 'bar', 'beer'] %}
        ...
    {% endif %}
    
    0 讨论(0)
  • 2020-12-12 12:23

    Though The above answers are right, I found something more user-friendly approach while using ternary operator.

    {{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
    

    If someone need to work through foreach then,

    {% for attachment in attachments %}
        {{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-12 12:29

    another example following @jake stayman:

    {% for key, item in row.divs %}
        {% if (key not in [1,2,9]) %} // eliminate element 1,2,9
            <li>{{ item }}</li>
        {% endif %}
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-12 12:34

    You just have to change the second line of your second code-block from

    {% if myVar is in_array(array_keys(someOtherArray)) %}
    

    to

    {% if myVar in someOtherArray|keys %}
    

    in is the containment-operator and keys a filter that returns an arrays keys.

    0 讨论(0)
  • 2020-12-12 12:38

    It should help you.

    {% for user in users if user.active and user.id not 1 %}
       {{ user.name }}
    {% endfor %}
    

    More info: http://twig.sensiolabs.org/doc/tags/for.html

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