3

I'd like to create a variable from another variable. What I got right now is something like this:

{% set language = fr %} 
{% if language == "en"  %}
   {% set fooAddress = en_foobar.globalAddress %} 
{% if language == "fr"  %}
   {% set fooAddress = fr_foobar.globalAddress %}
{% if language == "de"  %}
   {% set fooAddress = de_foobar.globalAddress %} 

What I'd like to do is:

{% set fooAddress = language  ~ "_foobar.globalAddress" %}

No problem with plain PHP (http://php.net/manual/en/language.variables.variable.php) but is this possible to do with Twig?

1 Answer 1

4

In order to pull this off, you'll need to take advantage of the not very well documented _context variable in Twig. This should do it:

{% set language = 'fr' %}

{% set foobar = _context[language ~ "_foobar"] is defined ? _context[language ~ "_foobar"] : null %}

{% if foobar %}
    {{ foobar.globalAddress }}
{% endif %}
6
  • tried it that way, but i get this in response: Impossible to access an attribute ("globalAddress") on a string variable ("fr_foobar") Jan 22, 2016 at 8:06
  • Updated the answer and actually tested this one. :)
    – Brad Bell
    Jan 22, 2016 at 18:31
  • 3
    _context documentation, such as it is, is here: twig.sensiolabs.org/doc/tags/macro.html Jan 26, 2016 at 19:48
  • @BradBell ...and I had hoped to see the first example where the attribute function works attribute(foo, bar) and the subscript syntax foo[bar] doesn't.
    – carlcs
    Jan 26, 2016 at 21:45
  • @MarionNewlevant nice... linked to it.
    – Brad Bell
    Jan 26, 2016 at 22:04

Your Answer

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

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