Вопрос

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 %}
Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top