Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of string in Jinja/Flask

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?

like image 275
wuxiekeji Avatar asked Jun 11 '14 12:06

wuxiekeji


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.

Does flask include Jinja?

By default, Flask uses Jinja2 as its template engine.

What is Jinja2 syntax?

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.


1 Answers

You can use the length filter:

{% if some_var|length > 1 %} 
like image 156
Martijn Pieters Avatar answered Sep 22 '22 12:09

Martijn Pieters