455

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>
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
flybywire
  • 261,858
  • 191
  • 397
  • 503

5 Answers5

797
<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")

tshepang
  • 12,111
  • 21
  • 91
  • 136
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 1
    Can we check for undefined too? I have to use {% if products is none ... %} which is quite tiring – Nam G VU Aug 21 '17 at 04:28
  • 3
    @wvxvw this does work: `{% set item_count = items | length %}` as long as `items` is a list, dict, etc. – kbolino May 14 '19 at 17:51
  • Thanks @AlexMartelli. In addition we could use inline syntax like `{{ form.select_field(size=5 if form.select_field.choices|count > 5 else form.select_field.choices|count) }}` – Filipe Bezerra de Sousa Jun 28 '20 at 23:52
16

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 %}
Ashwin
  • 2,875
  • 1
  • 13
  • 21
  • 1
    You can loop through your collection in pythonic way: ```{% for user in nums['list_users_response']['list_users_result']['users'] %}
  • {{ user['user_name'] }}
  • {% endfor %}``` – dmitry_romanov Jul 04 '21 at 10:48