除了最后一个元素之外,在列表的每个元素之后添加逗号的最短(也是最清晰)方法是什么?
{% for role in user.roles %}
{{ role.name }},
{% endfor %}
此示例将在所有行之后添加逗号,包括最后一行。
答案 0 :(得分:78)
不知道最短,但这可能很清楚。尝试以下操作在循环中除最后一行之外的所有行之后添加逗号:
{% for role in user.roles %}
{{ role.name }}
{% if not loop.last %},{% endif %}
{% endfor %}
答案 1 :(得分:20)
这适用于Symfony 2.3.x但适用于每个2.x版本:
{{ user.roles|join(', ') }}
答案 2 :(得分:2)
{{-不是loop.last吗? ',':''-}}
答案 3 :(得分:1)
{{user.roles | column('title')| join(',')}}
答案 4 :(得分:0)
这是我设法在某些科学出版物中用作者姓名命名的方法。将值存储在重复的字段中,然后fields.html.twig像这样-
{% spaceless %}
{% for item in items %}
{{- loop.last ? ' and ' : (not loop.first ? ', ') -}}
{{- item.content -}}
{% endfor %}
{% endspaceless %}
答案 5 :(得分:0)
由于OP要求迭代name
的{{1}}键。
最短的时间是:
role
其中{{ user.roles|column('name')|join(', ') }}
是用户角色的列表。