How to output a comma delimited list in jinja python template?

此生再无相见时 提交于 2019-12-18 09:56:09

问题


If I have a list of users say ["Sam", "Bob", "Joe"], I want to do something where I can output in my jinja template file:

{% for user in userlist %}
    <a href="/profile/{{ user }}/">{{ user }}</a>
    {% if !loop.last %}
        , 
    {% endif %}
{% endfor %}   

I want to make the output template be:

Sam, Bob, Joe

I tried the above code to check if it was on the last iteration of the loop and if not, then don't insert a comma, but it does not work. How do I do this?


回答1:


You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ "," if not loop.last }}



回答2:


you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:

{{ users|join(', ') }}



回答3:


And using the joiner from http://jinja.pocoo.org/docs/dev/templates/#joiner

{% set comma = joiner(",") %}
{% for user in userlist %}
    {{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}  

It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.

A more complex example on why you would use it.

{% 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 %}



回答4:


The following code worked using jinja2 join filter Uli Martens suggested in python3.5 shell:

>>> users = ["Sam", "Bob", "Joe"]
>>> from jinja2 import Template
>>> template = Template("{{ users|join(', ') }}")
>>> template.render(users=users)
'Sam, Bob, Joe'


来源:https://stackoverflow.com/questions/11974318/how-to-output-a-comma-delimited-list-in-jinja-python-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!