Testing for a List in Jinja2

送分小仙女□ 提交于 2019-12-18 18:41:46

问题


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.


回答1:


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



回答2:


I did it like this:

{% if var is iterable and var is not string %}



回答3:


Jinja has many builtin tests. You are probably looking for iterable.

{% if var is iterable %}



回答4:


In my setup, I'd like for a value to either be a string or list of strings coming into the Jinja template. So really what I cared about wasn't string vs list, but single item vs multiple items. This answer might help if your use case is similar.

Since there isn't a built-in test for "is list?" that also rejects strings, I borrowed a pattern from API design and wrapped the single objects in a list on the Python side then checked list length on the Jinja side.

Python:

context = { ... }

# ex. value = 'a', or ['a', 'b']
if not isinstance(value, list):
    value = [value]

context['foo'] = value

Jinja:

{% if foo|length == 1 %}
  single-item list
{% elif foo|length > 1 %}
  multi-item list
{% endif %}

And if all you want to do is add an item separator for display purposes, you can skip the explicit length check and just {{ value|join(', ') }}.



来源:https://stackoverflow.com/questions/11947325/testing-for-a-list-in-jinja2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!