Get lengths of a list in a jinja2 template

flybywire picture flybywire · Sep 23, 2009 · Viewed 268.6k times · Source

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>

Answer

Alex Martelli picture Alex Martelli · Sep 23, 2009
<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")