使用 Twig 在数组的值上添加逗号

Add a comma on Values of an Array with Twig

当我通过 Twig 显示它时,我想在每个数组值之间放置一个变量。

这是我的代码:

{% for genre in genres %}
    {% for namez in genre.name|split(', ') %}
        <span>{{ namez }}</span>
    {% endfor %}
{% endfor %}

数组结构流派 :

array (size=2)
  0 =>
    array (size=4)
      'id' => string '2' (length=1)
      'name' => string 'Documentaire' (length=12)
      'movie_id' => string '2' (length=1)
      'genre_id' => string '2' (length=1)
  1 =>
    array (size=4)
      'id' => string '3' (length=1)
      'name' => string 'Animation' (length=9)
      'movie_id' => string '2' (length=1)
      'genre_id' => string '3' (length=1)

我的成绩:纪录片动作剧情片

而不是:纪录片、动作片、剧情片

也许即使可以在 Twig / PHP split() 函数上应用 sort() PHP 函数。

您不能从 twig 中的数组中提取特定子键的值。你可以使用循环变量做你想做的事

{% for genre in genres %}
    {{ genre.name }}{% if not loop.last %}, {% endif %}
{% endfor %}

https://twig.symfony.com/doc/3.x/tags/for.html

您绝对可以使用 map 过滤器一次完成此操作而无需循环。

{{ genres | map(genre => "#{genre.name}") | join(', ') }}

对于您的示例数组,会给出:

Documentaire, Animation

这里可以测试:https://twigfiddle.com/sjd56x

尝试循环

{% for genre in genres %}
    {{ genre.name }} {{ not loop.last ? ',' }}
{% endfor %}