首页 文章

在jinja2模板中获取列表的长度

提问于
浏览
222

如何获取jinja2模板中列表中的元素数量?

例如,在Python中:

print(template.render(products=[???]))

在jinja2

<span>You have {{what goes here?}} products</span>

2 回答

  • 383
    <span>You have {{products|length}} products</span>
    

    您也可以在表达式中使用此语法

    {% if products|length > 1 %}
    

    jinja2的内置过滤器记录在案here;具体而言,正如您已经发现的那样,length(及其同义词 count )记录在:

    返回序列或映射的项目数 .

    所以,再次如您所见,模板中的 {{products|count}} (或等效 {{products|length}} )将给出"number of products"("length of list")

  • 5

    亚历克斯的评论看起来不错,但我仍然对使用范围感到困惑 . 以下工作适用于使用范围内长度的条件 .

    {% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
    <li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
    {% endfor %}
    

相关问题