简体   繁体   English

树枝中的逗号分隔列表

[英]Comma separated list in twig

What is the shortest (and clearest) way to add comma after each element of the list except the last one?除了最后一个元素之外,在列表的每个元素之后添加逗号的最短(和最清晰)方法是什么?

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

This example will add comma after all lines, including the last one.此示例将在所有行后添加逗号,包括最后一行。

Don't know about shortest but this could be clear.不知道最短,但这可能很清楚。 Try the following to add comma after all lines in the loop except the last one:尝试以下方法在循环中除最后一行之外的所有行后添加逗号:

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

Shorter version as suggested in comments:评论中建议的较短版本:

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

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

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

{{- not loop.last ? {{- 不是 loop.last ? ',' : '' -}} ',' : '' -}}

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

Since the OP asked for iterating on name key of a role .由于 OP 要求迭代role name键。

Shortest would be:最短的是:

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

where user.roles is a list of user roles.其中user.roles是用户角色列表。

Here is how I managed to print author names (in authors array) in some scientific publication format using twig's local loop variable in for loop-这是我如何使用 twig 的局部loop变量在for loopfor某种科学出版物格式打印作者姓名(在authors数组中) -

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

The output is something like输出是这样的

  • For 1 author对于 1 个作者

    Author1作者 1

  • For 2 authors 2位作者

    Author1 and Author2作者 1 和作者 2

  • For 3 or more authors对于 3 个或更多作者

    Author1, Author2, and Author3作者 1、作者 2 和作者 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM