Search code examples
pythonpython-3.xtemplatesjinja2

Get value from dict after applying filter Jinja2


I use Jinja2 template, with dictionary. Here examples:

My dictionary:

context = {
    "lead":{
        "name": "Cool lead with top sale",
        "sale": 1
    },
    "contacts": [
        {
            "name": "John Doe",
            "tags": ['vasya']
        },
        {
            "name": "Nick Snow",
            "tags": ['petya']
        }
    ]
}

I want to get a contact name, but only one, that has tag 'petya'. I created a filter:

def has_tag(entity, tagname):
    contact = list(filter(lambda x: tagname in x['tags'], entity))[0]
    return contact

Finally, I want to access the value in my template by something, like this:

{{ contacts | has_tag('petya') .name }} 

or

{{ contacts | has_tag('petya') | .name }} 

But I cannot understand - how I can do this? Because | uses only to filters. I cannot use selectattr, because there can be a lot of nested dicts, like contacts.responsible_user.phone.mobile etc.

Please give me advice, how I can do this. Thanks!


Solution

  • Use {% set %} to assign the filtered contact to a variable:

    {% set petya = contacts | has_tag('petya') %}
    {% if petya %}
      {{ petya.responsible_user.phone.mobile }}
    {% endif %}