The Jinja context is a namespace; so yes, you have to use a dictionary, otherwise the values are not bound to names for you to refer to in your template.
Jinja: Context as Array
Вопрос
Can a Jinja2 context only be a dictionary? In many cases I don't have {'something': [1, 2, 3]}
but simply [1, 2, 3]
.
Am I forced to wrap the list into a dictionary in order to loop through it?
EDIT: If someone finds it useful, I ended up passing every the context to the following function so that it leaves a dictionary unchanged, but wraps lists in a {'this': [MY_ARRAY]}
structure.
def checked_context(ctx):
return ctx if isinstance(ctx, dict) else {'this': ctx}
Basically, you keep using dictionaries as normal, and can access lists with this
like in the following example that handles a simple list such as [1, 2, 3]
:
{% for number in this %}
{{ number }}
{% endfor %}
Решение
Не связан с StackOverflow