New to twig and haven't found a great answer so far on this one:
I have an associative array of TimberMenus in the Timber context and each one corresponds to a different WordPress menu via the menu id.
In the Twig file I want a dynamic check to select which menu should be displayed, and evaluate the menu_name variable.
{% if menus.{{menu_name}}.items %}
So if menu_name = 'academics', I'd like the above code to evaluate to:
{% if menus.academics.items %}
The above doesn't work and I can't seem to find how I would accomplish this within Twig.
Any ideas or help very welcome!
As described in the variables section you can use the "subscript" syntax ([]), as example:
{%set menu_name = 'academics'%}
{{menus[menu_name].items}}
Check this working example
Hope this help
There is attribute function, that allow to access dynamic properties:
{% if attribute(menus, menu_name).items %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With