Jinja2 check if value exists in list of dictionaries

孤人 提交于 2021-02-09 00:26:33

问题


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 :-).


回答1:


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.



来源:https://stackoverflow.com/questions/52226293/jinja2-check-if-value-exists-in-list-of-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!