用逗号分隔的小树枝列表


Comma separated list in twig

除了最后一个元素之外,在列表的每个元素后面添加逗号的最短(最清晰)方法是什么?

{% for role in user.roles %}
    {{ role.name }},
{% endfor %}

本例将在所有行后面添加逗号,包括最后一行。

不知道最短,但这可能很清楚。尝试以下操作在循环中除最后一行外的所有行后面添加逗号:

{% for role in user.roles %}
    {{ role.name }}
    {% if not loop.last %},{% endif %}
{% endfor %}

意见中建议的较短版本:

{% for role in user.roles %}
    {{ role.name }}
    {{ not loop.last ? ',' }}
{% endfor %}

这适用于Symfony 2.3.x,但应适用于每个2.x版本:

{{ user.roles|join(', ') }}

{{-not loop.last?',':"-}}

{{user.roles|column('title')|join(',')}}

因为OP要求对rolename密钥进行迭代。

最短的是:

{{ user.roles|column('name')|join(', ') }}

其中CCD_ 3是用户角色的列表。

以下是我如何在for循环-中使用trick的本地loop变量以某种科学出版物格式打印作者姓名(在authors数组中)

    {% spaceless %}
     {% for author in authors %}
      {{- loop.last ? ' and ' : (not loop.first ? ', ') -}}
      {{- author -}}
     {% endfor %}
    {% endspaceless %}

输出类似

  • 对于1位作者

    Author1

  • 对于2位作者

    Author1和Author2

  • 对于3个或更多作者

    Author1、Author2和Author3