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.
Setting Flag in Twig
Creating a Custom Filter in PHP
To reduce the code in your templates twig has the opportunity to create custom filters. To achieve a more general functionality you can simply use variable variable names and use the attribute name as another parameter.
PHP
Twig
this one is more like a multidimensional loop in case it's necessary
{% if myVar is xpath_aware('//tags/*[id=20]') %}
Context
If you are going to do conditions on an arbitrary deep array, why not using the power of
xpath
? An array is no more than an unserialized XML string after all!So, the following array:
Is the equivalent of the XML string (fixed to avoid numeric tags):
And you want to know if your array matches the following xpath expression:
Implementation
We create a new twig Test that will convert our array into a
SimpleXMLElement
object, and useSimpleXMLElement::xpath()
to check if a given xpath matches.We are now able to run the following test in Twig:
Full executable implementation:
xpath_test.php
To run it
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:
---- EDIT ----
FOR ELSE
To do an
else
. So theelse
here is if nothing is found in the entirefor
:FOR-IF ELSE
Making a combination of the
if
andelse
is possible, but it is NOT the same as anif
else
inside thefor
loop. Because theelse
is for thefor
and not for theif
.LIVE example
FOR-IF ELSE and IF ELSE
LIVE example
TWIG documentation
I found myself the solution. Didn't expect it to be so simple. Sometimes I guess I just try to make things too complicated.
In my opinion this is not the most efficient way but it does the trick for me at the moment.
Edit
Yenne Info tipped me about the following method. It's a bit cleaner. I don't know if it improves performance though.
Set a flag and use a loop. Afterwards you can use the flag in if conditions.