我使用Jinja2模板,带有字典。这里的例子:
我的字典:
context = {
"lead":{
"name": "Cool lead with top sale",
"sale": 1
},
"contacts": [
{
"name": "John Doe",
"tags": ['vasya']
},
{
"name": "Nick Snow",
"tags": ['petya']
}
]
}
我想得到一个联系人的名字,但只有一个,标签是"petya"。我创建了一个过滤器:
def has_tag(entity, tagname):
contact = list(filter(lambda x: tagname in x['tags'], entity))[0]
return contact
最后,我想通过以下方式访问模板中的值:
{{ contacts | has_tag('petya') .name }}
或
{{ contacts | has_tag('petya') | .name }}
但我不能理解——我怎么能做到这一点?因为|
仅用于筛选。我不能使用selectattr,因为可能有很多嵌套的dict,如contacts.responsible_user.phone.mobile
等。
请给我建议,我该怎么做。谢谢
使用{% set %}
将过滤后的联系人分配给变量:
{% set petya = contacts | has_tag('petya') %}
{% if petya %}
{{ petya.responsible_user.phone.mobile }}
{% endif %}