How do you translate the elements of an array and join them?

Using a twig, how can I translate all the elements in an array and connect them to a slash? Do I need to use an additional variable or is there a smarter method?

At the moment I am doing something like this:

{% set labels = [] %} {% for feature in menu_item.features %} {% set labels = labels|merge([feature|trans([], 'features')]) %} {% endfor %} {{ labels | join(' / ')}} 

This sucks.

+4
source share
2 answers

Why not just output the contents during the loop?

 {% for feature in menu_item.features %} {% if loop.index0 > 0 %}/{% endif %} {{feature|trans}} {% endfor %} 
+3
source

Not everything has to be done in a "view."

This type of code is probably much better placed in the logic of your controller, and then passed to the view as a merged + merged result. Because in your example, all you do is compile the result, which is easier to do in the code.

0
source

Source: https://habr.com/ru/post/1390436/


All Articles