简体   繁体   中英

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. 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"

<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. 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]) is a lot easier to follow at first glance than the other 2 options.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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