Skip to content
Advertisement

How do I filter a list through a lookup dictionary in jinja2

How can I filter a list in jinja2 to generate a list of values from a lookup table?

I have a situation where I am using Jinja2 to generate SQL. I have a list of values and I want to replace them with a list of transformed values based on a lookup:

In my template, I want to be able to use do something like this using filters instead of a loop:

The trailing comma will lead to SQL that is not well formed.

I want to avoid creating a customer filter, but I haven’t come across a filter that can find a dictionary reference the way I need:

I can’t use map(attribute=*) for some_lookup_method because I don’t know how to access the key that comes from start_values. Most examples online are for Ansible and use a flattened structure, like the one below. I do not want that structure so please no answers for that format.

Advertisement

Answer

There is, sadly, no such a filter in native Jinja to filter a dictionary or to make a list out of a dictionary, like the answers you found for Ansible, that are using dict2items.

This said, using loop.last, you could conditionally add the comma or not:

Would give you

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement