Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get lengths of a list in a jinja2 template

Tags:

python

jinja2

How do I get the number of elements in a list in jinja2 template?

For example, in Python:

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

and in jinja2

<span>You have {{what goes here?}} products</span> 
like image 203
flybywire Avatar asked Sep 23 '09 10:09

flybywire


People also ask

How do I find the length of a list in Jinja?

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count ) is documented to: Return the number of items of a sequence or mapping. @wvxvw this does work: {% set item_count = items | length %} as long as items is a list, dict, etc.

How do you iterate through a list in Jinja?

To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.

What is Autoescape in Jinja2?

B701: Test for not auto escaping in jinja2When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.


2 Answers

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

You can also use this syntax in expressions like

{% if products|length > 1 %} 

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

like image 148
Alex Martelli Avatar answered Oct 21 '22 15:10

Alex Martelli


Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% 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 %} 
like image 31
Ashwin Avatar answered Oct 21 '22 15:10

Ashwin