Dowemo
0 0 0 0


Question:

To simply check if an array contains a certain value I would do:

{% if myVar in someOtherArray|keys %}
...
{% endif %}

However, my array is multi-dimensional.

$tasks = array(
    'someKey' => 'someValue',
    ...
    'tags' => array(
        '0' => array(
            'id'   => '20',
            'name' => 'someTag',
        ),
        '1' => array(
            'id'   => '30',
            'name' => 'someOtherTag',
        ),
    ),
);

What i would like is to be able to check if the $tasks['tags'] has tag id 20. I hope I'm not confusing you by using the PHP array format.


Best Answer:


For an if-statement within a multi-dimensional array in Twig. Check within the for-loop and then the if statement.

Here is the shorthand for this with Twig:

{% for tag in tasks.tags if tag.id == '20' %}      
       here_if_true
{% endfor %}    

---- EDIT ----

FOR ELSE

To do an else. So the else here is if nothing is found in the entire for:

{% for tag in tasks.tags %}    
       here_if_true
{% else %}
       if there was nothing found
{% endfor %}    

FOR-IF ELSE

Making a combination of the if and else is possible, but it is NOT the same as an ifelse inside the for loop. Because the else is for the for and not for the if.

{% for tag in tasks.tags if tag.name == 'blue' %}      
    This will fire if in the FOR the tag.name that is blue
{% else %}
    This will fire if there were NO tag.name blue were found ENTIRE FOR!
{% endfor %}

LIVE example

FOR-IF ELSE and IF ELSE

{% for tag in tasks.tags if tag.id == 3 %}    
    the id is 3
    {% if tag.name == 'blue' %}
    the id of the tag is 3 and tag.name is blue
    {% else %} 
    the id of the tag is 3 but the tag.name is not blue
    {% endif %}
{% else %}
    there was no tag.id 3 found in the tasks.tags
{% endfor %}

LIVE example

TWIG documentation




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs