简体   繁体   English

如何在 Jinja2 中测试列表?

[英]How to test 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.据我所知,在 Jinja2 中没有办法测试一个对象是否是List实例。

Is that correct and has anyone implemented a custom test/extension in Jinja2?这是正确的,有人在 Jinja2 中实现了自定义测试/扩展吗?

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 .您可以在此处找到所有 jinja 测试的列表。

You can easily do this whit a custom filter in jinja2.您可以使用 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,
})

In my setup, I'd like for a value to either be a string or list of strings coming into the Jinja template.在我的设置中,我希望值可以是进入 Jinja 模板的字符串或字符串列表。 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?"由于没有针对“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.这也拒绝字符串,我从 API 设计中借用了一个模式,并将单个对象包装在 Python 端的列表中,然后检查 Jinja 端的列表长度。

Python: 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(', ') }} .如果您只想添加一个用于显示目的的项目分隔符,您可以跳过显式长度检查而只需{{ value|join(', ') }}

Iterable return True also on dict. Iterable 也在 dict 上返回 True。 Try this:尝试这个:

{% if var.__class__.__name__ == 'list' %}

Jinja has many builtin tests. Jinja 有许多内置测试。 You are probably looking for iterable .您可能正在寻找iterable

{% if var is iterable %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM