Your Location is: Home > Symfony

Translate dynamic variable in twig

From: Skopje View: 3696 ancient_bonus 

Question

How do I translate this in twig? I have this variable in twig that is an array:

$array = [
  ['number' => 7, 'name' => 'foo'],
  ['number' => 8, 'name' => 'bar'],
  ['number' => 10, 'name' => 'baz'],
  // ... and so on and so forth
]

Would like it to be something like this:

The variables are 7 times for foo, 8 times for bar, and 10 times for baz.

Or

The variables are 7 times for foo and 10 times for baz.

Or

The variable is 7 times for foo.

Tried with something like this:

    {% set last = array|last %}
    {% set array = array|slice(0, array.length - 1) %}

    {% trans %}
      <p>The variables are
        {% for i in array %}
          {{ i.number }} times {{ i.name }},
        {% endfor %}
        , and {{ last.number }} number of {{ last.name }}
      .</p>
    {% endtrans %}

Thanks!

Best answer