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?
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.
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.
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.
This works for me (Jinja 2.7):
{% if {}|length == 0 %}
is zero
{% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With