Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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": "[email protected]",
        "rol": "admin"
    },
    {
        "name": "John Smith",
        "email": "[email protected]",
        "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 :-).

like image 659
mrroot5 Avatar asked Sep 07 '18 16:09

mrroot5


1 Answers

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.

like image 139
Joost Avatar answered Nov 06 '22 19:11

Joost