Cnote
Cnote

Reputation: 33

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!

Upvotes: 3

Views: 2317

Answers (2)

jkucharovic
jkucharovic

Reputation: 4244

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

{% if attribute(menus, menu_name).items %}

Upvotes: 2

Matteo
Matteo

Reputation: 39380

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

Upvotes: 6

Related Questions