Jinja unfortunately does not support executing arbitrary Python code, such as
{% if len(some_var)>1 %} ... {% endif %}
My current workaround is to use the deprecated, ugly, double-underscore method:
{% if some_var.__len__()>1 %} ... {% endif %}
Although this works, I'm afraid that some future implementation of strings might break this code. Is there a better way to do this?
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.
By default, Flask uses Jinja2 as its template engine.
Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.
You can use the length
filter:
{% if some_var|length > 1 %}
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