Get lengths of a list in a jinja2 template

Viewed 377813

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>
4 Answers

I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()

My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:

{{'0' if linked_contacts == None else linked_contacts|length}}

If for loop with array is used then you can use the following

{% for i in range(array|length) %}
          array[i]
{% endfor %}
Related