I'm trying to access a property with a $
in its name in a django template. Unfortunately I have no control over filters nor over the variable names.
The object is structured as follows:
{
"title": "Some title",
"metadata": {
"$price": 9.99,
"$inventory_policy": 1
}
}
I am trying to access {{ item.metatadata.$price }}
, but the template builder crashes with an unspecified error.
I already tried the workarounds for python templates, but they crash as well:
{{ item.metatadata.$$price }}
{{ item.metatadata.${price} }}
For future reference, this is in a Klaviyo template.
CodePudding user response:
I think you can use a custom filter for doing that : https://docs.djangoproject.com/fr/4.1/howto/custom-template-tags/
in templatetags.extras.py
from django import template
register = template.Library()
@register.filter
def get_value(dictio, key):
return dictio.get(key, '')
and for using it:
{% load extras %}
{{ item.metatadata|get_value:"$price" }}
CodePudding user response:
Nevermind. They supply an undocumented lookup
filter for exactly that reason. It probably looks exactly like in Lucas Grugru's answer.
{{ item.metatadata|lookup:"$price" }}
The relevant section in the Klaviyo documentation is https://help.klaviyo.com/hc/en-us/articles/115005084927-Guide-to-Template-Tags-and-Variable-Syntax#event-variables-4, where the lookup
filter is used in an unrelated example.