Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for a List in Jinja2?

Tags:

python

jinja2

As far as I can see, there is no way to test if an object is a List instance in Jinja2.

Is that correct and has anyone implemented a custom test/extension in Jinja2?

like image 811
MFB Avatar asked Aug 14 '12 07:08

MFB


People also ask

How do I find the length of a list in Jinja?

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.

How use Jinja safe filter?

The safe filter explicitly marks a string as "safe", i.e., it should not be automatically-escaped if auto-escaping is enabled. The documentation on this filter is here. See the section on manual escaping to see which characters qualify for escaping.

What is Autoescape in Jinja2?

When autoescaping is enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables. Without escaping HTML input the application becomes vulnerable to Cross Site Scripting (XSS) attacks. Unfortunately, autoescaping is False by default.


2 Answers

I did it like this:

{% if var is iterable and (var is not string and var is not mapping) %} 

You can find a list of all jinja tests here.

like image 131
insider Avatar answered Sep 28 '22 08:09

insider


You can easily do this whit a custom filter in jinja2.

First create you test method:

def is_list(value):     return isinstance(value, list) 

And add it as an custom filter:

j = jinja2.Jinja2(app) j.environment.filters.update({         'is_list': is_list, }) 
like image 28
fredrik Avatar answered Sep 28 '22 09:09

fredrik