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

前端 未结 3 862
半阙折子戏
半阙折子戏 2020-12-22 16:56

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:

{%          


        
相关标签:
3条回答
  • 2020-12-22 17:18

    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 }}
    
    0 讨论(0)
  • 2020-12-22 17:19

    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 %}
    
    0 讨论(0)
  • 2020-12-22 17:20

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

    {{ users|join(', ') }}
    
    0 讨论(0)
提交回复
热议问题