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?

3

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 %}
| improve this answer | |
  • tried it that way, but i get this in response: Impossible to access an attribute ("globalAddress") on a string variable ("fr_foobar") – Stefan Friedrich Jan 22 '16 at 8:06
  • Updated the answer and actually tested this one. :) – Brad Bell Jan 22 '16 at 18:31
  • 3
    _context documentation, such as it is, is here: twig.sensiolabs.org/doc/tags/macro.html – Marion Newlevant Jan 26 '16 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 '16 at 21:45
  • @MarionNewlevant nice... linked to it. – Brad Bell Jan 26 '16 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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