1
Jinja2ののcontextfilterから変数へのアクセス方法(簡体字):これは、ことができます私は、次のフィルタに基づいてJinja2のでカスタム国際化システムを開発しました
@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)
私は、例えば、次のものを作成しますコンテキスト:私のテンプレートでは、このような
context = {
'user': {
'name': 'Joel',
'locale': 'es'
}
'greetings': {
'en': 'Hi {{user.name}}!',
'es': '¡Hola {{user.name}}!'
}
}
そして、それを使用します。完璧に動作
{{ greetings[user.locale]|render() }}
。
ここでは、1つのユーザーの代わりにユーザーの配列があるとします。私は、Djangoのテンプレートに次のようにやっていたが、変数「ユーザーが」コンテキストではないので、それはJinja2のでは動作しません:
{% for user in list_of_users %}
{{ greetings[user.locale]|render() }}
{% endfor %}
は、私は新しい変数(ユーザー)を追加するために何ができるものはあります私がコンテキストフィルタで使用するコンテキストに?私はそれが機能したい場合は、その名前と価値の両方を追加する必要があります。
ありがとうございました。