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>
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>
<span>You have {{product|length}} products</span>
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")
I think it's helpful, when feasible, to provide precise links to docs in an answer (as well as the immediate answer to the specific question asked) -- this way, one gets some idea of roughly where to look in the docs for future answers to similar questions (as well as immediate help for one's specific problem, where needed).