如何获取jinja2模板列表中的元素个数?
例如,在 Python 中:
print(template.render(products=[???]))
在 jinja2 中
<span>You have {{what goes here?}} products</span>
最佳答案
<span>You have {{products|length}} products</span>
你也可以在表达式中使用这种语法
{% if products|length > 1 %}
jinja2 的内置过滤器有文档记录 here ;具体来说,正如您已经发现的那样,length
(及其同义词 count
)记录到:
Return the number of items of a sequence or mapping.
所以,正如您所发现的,模板中的 {{products|count}}
(或等效的 {{products|length}}
)将给出“产品数量”(“列表长度”)
关于python - 获取 jinja2 模板中列表的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1465249/