Reputation: 15
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;
Upvotes: 1
Views: 3137
Reputation: 15
@Darabee.
You are correct, the syntax would be:
{{ attribute(_context, 'content_' ~ page.lang) }}
But how ever I noticed that if there is a array and u use '.' instead of a underscore '_' it will not work.
In my case I have a multi-array. That is the issue.
page['city']['content_en'].
or page.city.content_en
Upvotes: 0
Reputation: 15650
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
Upvotes: 2