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?
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.
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.
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.
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.
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, })
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