Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing length of dictionary in jinja flask template

I pass the dictionary errs to a jinja template for flask server:

{% if  not errs|length  equals 0  %}

But, the following error occurs:

TemplateSyntaxError: expected token 'end of statement block', got 'equals'

I tried various combinations but keep getting different errors, so how to compare length of a dictionary in the template if construct?

like image 983
stackit Avatar asked Oct 21 '13 10:10

stackit


People also ask

How do I find the length of a Jinja template?

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.

Can you check the length of a dictionary Python?

To check the length of a Python dictionary, we can easily use Python's built-in function len(). This function gives the number of lengths which is available in the dictionary in the form of key-value pairs. Len() function always return the number of iterable items given in the dictionary.

Which function returns the length of the dictionary?

The len() function is widely used to determine the size of objects in Python. In our case, passing a dictionary object to this function will return the size of the dictionary i.e. the number of key-value pairs present in the dictionary.


1 Answers

This works for me (Jinja 2.7):

{% if {}|length == 0 %}
    is zero
{% endif %}
like image 195
DazWorrall Avatar answered Sep 27 '22 23:09

DazWorrall