Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig evaluate variable within variable?

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!

like image 958
Cnote Avatar asked Apr 17 '26 19:04

Cnote


2 Answers

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

like image 85
Matteo Avatar answered Apr 19 '26 09:04

Matteo


There is attribute function, that allow to access dynamic properties:

{% if attribute(menus, menu_name).items %}
like image 20
jkucharovic Avatar answered Apr 19 '26 10:04

jkucharovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!