I’ve developed a custom i18n system in Jinja2 based on the following filter (simplified):
@contextfilter
def render(context, value):
"""
Renders the filtered value as a string template, using the context
and environment of the caller template.
"""
mini_template = _environment.from_string(value)
return mini_template.render(context)
This allows me, for example, to create the following context:
context = {
'user': {
'name': 'Joel',
'locale': 'es'
}
'greetings': {
'en': 'Hi {{user.name}}!',
'es': '¡Hola {{user.name}}!'
}
}
And use it like this in my templates:
{{ greetings[user.locale]|render() }}
That works perfectly.
Now imagine that I’ve an array of users instead of a single one. I was doing the following in Django Templates, but it doesn’t work in Jinja2 because the variable ‘user’ is not in the context:
{% for user in list_of_users %}
{{ greetings[user.locale]|render() }}
{% endfor %}
Is there anything I could do to add the new variable (user) to the context I use at the contextfilter? I need to add both its name and value if I want it to work.
Thank you very much for your help.
Ok, I’ve fixed it using kwargs (although it’s more verbose than its equivalente in Django templates).
Filter:
Usage: