Jinja2检查字典列表中是否存在值 [英] Jinja2 check if value exists in list of dictionaries

查看:532
本文介绍了Jinja2检查字典列表中是否存在值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查包含字典的列表中是否存在值.我使用烧瓶1.0.2.请参见下面的示例:

I am trying to check if a value exists inside a list with dictionaries. I use flask 1.0.2. See example below:

person_list_dict = [
    {
        "name": "John Doe",
        "email": "johndoe@mydomain.com",
        "rol": "admin"
    },
    {
        "name": "John Smith",
        "email": "johnsmith@mydomain.com",
        "rol": "user"
    }
]

我找到了解决此问题的两种方法,您能告诉我哪个更好吗?:

I found two ways to solve this problem, can you tell me which is better?:

<pre>{% if "admin" in person_list_dict|map(attribute="rol") %}YES{% else %}NOPE{% endif %}</pre>
# return YES (john doe) and NOPE (john smith)

第二个选项:烧瓶模板过滤器

烧瓶代码:

Second option: Flask template filter

Flask code:

@app.template_filter("is_in_list_dict")
def is_any(search="", list_dict=None, dict_key=""):
    if any(search in element[dict_key] for element in list_dict):
        return True
    return False

模板代码:

<pre>{% if "admin"|is_in_list_dict(person_list_dict, "rol") %} YES {% else %} NOPE {% endif %}</pre>
# return YES (john doe) and NOPE (john smith)

谢谢:-).

推荐答案

如果可能的话,在将其添加到Jinja中之前,我将把此逻辑移到脚本的python部分.因为,如 Jinja文档:毫无疑问,您应该尝试从模板中删除尽可能多的逻辑."

If possible, I would move this logic to the python part of the script before rendering it in Jinja. Because, as stated in the Jinja documentation: "Without a doubt you should try to remove as much logic from templates as possible."

any([person['role'] == 'admin' for person in person_dict_list])乍一看要容易得多.

如果这不是一个选择,我可能会使用第一个内置函数,因为我认为在您自己的解决方案中,不太可能在极端情况下出错,并且代码减少了大约6倍.

If that's not an option, I would probably use the first, build in function, because I think it's less prone to errors in edge cases as your own solution, and is about 6x less code.

这篇关于Jinja2检查字典列表中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆