Looping over subset in Jinja

前端 未结 1 1250
孤城傲影
孤城傲影 2021-02-19 08:15

Jinja allows me to do

{% for item in all_items %}
    {{ item }}
{% endfor %}

but I\'d like to be able to only take the first n items;

1条回答
  •  余生分开走
    2021-02-19 08:52

    You can use normal python slice syntax.

    >>> import jinja2
    >>> t = jinja2.Template("{% for i in items[:3] %}{{ i }}\n{% endfor %}")
    >>> items = range(10)
    >>> print(t.render(items=items))
    0
    1
    2
    

    0 讨论(0)
提交回复
热议问题