Andrew Slack Andrew Slack - 19 days ago 5
Twig Question

Getitng a Twig Lang value dynamically

I have a question about how I can pull a deep nested translation value from Twig dynamically.

Here is the setup:

I have my translations files in yml format (en.yml), here is an example:

parent:
child:
something: here is some test
another: more text here


I then have an array passed to Twig:

array(2) {
[0]=>
array(2) {
["name"]=>
string(2) "GS"
["folders"]=>
array(1) {
[0]=>
array(1) {
["name"]=>
string(3) "something"
}
}
[1]=>
array(2) {
["name"]=>
string(1) "I"
["folders"]=>
array(2) {
[0]=>
array(3) {
["name"]=>
string(2) "another"
}
}


In twig, I want to print the folder names to screen, e.g.

here is some test


It would be easy if the lang file had everything in its root, I could use:

{{ array.folders.name|trans }}


However as this is a nested value in the lang file I somehow need to say:

{{'parent.child'.array.folders.name|trans }}


Any help would be very much appricated.

Answer

Simply first concatenate the string, then pass the value to the translator filter as follow:

{{ ('parent.child.' ~ array.folders.name)|trans }}

Hope this help