Reputation: 351
I have a list of tables coming from a SQLite database:
tbls_name = db_admin.execute(
"""SELECT name FROM sqlite_master WHERE type='table';"""
)
And need to check if table_name
is in the resulting list of dictionaries.
In Python, I would do:
if table_name in [d['name'] for d in tbls_name]:
How can I do this in Jinja?
{% set tbl_valid = (table_name in [d['name'] for d in tbls_name]) %}
This throws an error.
Note that the tbls_name
is a list of dictionaries, e.g.:
[
{'name': 'tableName1'},
{'name': 'tableName2'},
{'name': 'tableName3'},
]
Upvotes: 2
Views: 315
Reputation: 39294
You can use the filter rejectattr
for this use case.
If the resulting list of dictionary still contains any item, then the queried table name is valid.
{% set tbls_name = [
{'name': 'foo'},
{'name': 'bar'},
{'name': 'baz'},
] -%}
{% set tableName = 'foo' -%}
{% if tbls_name | rejectattr('name', '!=', tableName) | list | length -%}
table name `{{ tableName }}` is valid
{% endif %}
Would yield:
table name `foo` is valid
Upvotes: 1