MFB MFB - 2 months ago 7
Python Question

Testing for a List in Jinja2

As far as I can see, there is no way to test if an object is a List instance in Jinja2. Firstly, is that correct and secondly, has anyone implemented a custom test/extension in Jinja2? Any help would be great.

Answer

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,
})
Comments