简体   繁体   English

Jinja2检查字典列表中是否存在值

[英]Jinja2 check if value exists in list of dictionaries

I am trying to check if a value exists inside a list with dictionaries. 我正在尝试检查包含字典的列表中是否存在值。 I use flask 1.0.2. 我使用烧瓶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?: 我找到了两种方法可以解决此问题,您能告诉我哪个更好吗?:

First option: jinja2 built-in template filter "map" 第一种选择:jinja2内置模板过滤器“地图”

<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

Template code: 模板代码:

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

Thanks :-). 谢谢 :-)。

If possible, I would move this logic to the python part of the script before rendering it in Jinja. 如果可能的话,在将其添加到Jinja中之前,我会将此逻辑移至脚本的python部分。 Because, as stated in the Jinja documentation : "Without a doubt you should try to remove as much logic from templates as possible." 因为,正如Jinja文档中所述:“毫无疑问,您应该尝试从模板中删除尽可能多的逻辑。”

any([person['role'] == 'admin' for person in person_dict_list]) is a lot easier to follow at first glance than the other 2 options. 与其他两个选项相比, any([person['role'] == 'admin' for person in person_dict_list])乍一看要容易得多。

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. 如果这不是一个选择,那么我可能会使用第一个内置函数,因为我认为它作为自己的解决方案在边缘情况下不太容易出错,并且代码减少了约6倍。

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

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