Jinja2 check if value exists in list of dictionaries
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.
mrroot5
Full Stack developer, in love with JavaScript and Python, specially Django, with a high motivation ratio
Updated on July 21, 2022Comments
-
mrroot5 almost 2 years
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 :-).
-
mrroot5 over 5 yearsI prefer the first options because it is developed by jinja and, as you say, it requires less code. Thanks Joost :-).
-
Luke Pighetti over 4 yearsWhenever I try to do this I keep getting the error
TemplateSyntaxError: expected token ',', got 'for'
, any ideas what I'm doing wrong? -
timle over 2 yearsLuke: The above example is meant to run in Python, before passing the list to Jinja. It will not run in Jinja.