如果我有一个名单users说["Sam", "Bob", "Joe"],我想要做的事,我可以在我的神社模板文件的输出:
{% for user in userlist %}
<a href="/profile/{{ user }}/">{{ user }}</a>
{% if !loop.last %}
,
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我想使输出模板为:
Sam, Bob, Joe
Run Code Online (Sandbox Code Playgroud)
我尝试了上面的代码来检查它是否在循环的最后一次迭代,如果没有,那么不要插入逗号,但它不起作用.我该怎么做呢?
Joe*_*Day 258
您希望您的if支票是:
{% if not loop.last %}
,
{% endif %}
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以使用If Expression缩短代码:
{{ "," if not loop.last }}
Run Code Online (Sandbox Code Playgroud)
小智 174
你也可以使用内置的"join"过滤器(http://jinja.pocoo.org/docs/templates/#join,如下所示:
{{ users|join(', ') }}
Run Code Online (Sandbox Code Playgroud)
dal*_*ore 61
并使用joiner从http://jinja.pocoo.org/docs/dev/templates/#joiner
{% set comma = joiner(",") %}
{% for user in userlist %}
{{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
它是为了这个目的而制作的.通常,对于单个列表来说,加入或检查forloop.last就足够了,但是对于多组事物来说它是有用的.
关于为什么要使用它的更复杂的例子.
{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
<a href="?action=edit">Edit</a>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87642 次 |
| 最近记录: |