如何在Jinja Python模板中输出逗号分隔列表? [英] How to output a comma delimited list in jinja python template?

查看:53
本文介绍了如何在Jinja Python模板中输出逗号分隔列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个users列表,例如["Sam", "Bob", "Joe"],我想做一些可以在我的jinja模板文件中输出的事情:

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

我要使输出模板为:

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?

推荐答案

您希望您的if支票是:

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

请注意,您还可以使用 If Expression 来缩短代码a>:

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

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

这篇关于如何在Jinja Python模板中输出逗号分隔列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆