6

I've got a parent template which contains the following code:

{% include '_layout' with {'countryCode': 'au'} %}

I have a global set with the handle au_Variables, and within that a field with the handle vimeoVideoId_au

The problem I'm having is with trying to render the following global: {{ au_Variables.vimeoVideoId_au }} dynamically, using the countryCode.

I've tried

{% set videoId = countryCode~'_Variables.vimeoVideoId_'~countryCode %}

And then outputting {{ videoId }} but all I get is the string au_Variables.vimeoVideoId_au, not the rendered global.

Any ideas how to do this in Twig?

2 Answers 2

5

Not sure if you saw this, but you may also be able to use the Twig attribute function:

{{ attribute(array, item) }}

Pretty straightforward, here's the official docs page...

2
  • Thanks. it was the property being dynamic too which was causing me to have all sorts of issues. Jul 3, 2014 at 3:52
  • Noting here an application of this function because it was not 'straightforward' to me until I hit upon the solution by trial and error! In my case the variable is the Globals field handle, so I've ended up with {{ attribute(globalSetHandle, globalsFieldVariable') }}, which works a treat. Mar 20, 2019 at 16:56
4

I've got a bit of a workaround, not sure if it's the best way to do it.

I restructured my fields, turns I don't need unique field names for the globals (still thinking in EE mode) so that took away half the problem.

I can access the global group dynamically, using _context

So after renaming my Video ID field, I can call the global set dynamically using:

{{ _context[countryCode~'_Variables'].vimeoId }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.