Search code examples
phptwigslimtwig-extension

How to use a variable in .twig syntax


I am to DRY in a twig template. I am wondering is you can access a variable in the {{ notation }} of twig.

For example:

{% if page.lang == 'en' %}
   // do something 
   {{ content_en }}
{% endif %}
{% if page.lang == 'es' %}
    // hacer algo 
    {{ content_es }}
{% endif %}

I tried some other approaches. But is it possible to (somehow) combine variables and do something like this:

// Php example
$var = 'content_';
$var .= page.lang;
// Output would be 'content_en';

But then for Twig?

// Something like 
{{ content_ + page.lang }}

To make it more clear. I would like to access to correct variable.

$content_en = 'this is just some content';
$content_es ='Alguna información';
$var = 'content_';
$var .= 'en';

$key = ${$var};
// Output is 'this is just some content'
echo $key;

Solution

  • If you want to concatenate the output you need to use ~

    {{ 'content_' ~ page.lang }}
    

    If you want to call a dynamic variable you need to use attribute

    {{ attribute(_context, 'content_' ~ page.lang) }}
    

    _context is a special variable in twig which containts all variables you passed towards the template