Frage

In my Jinja template I have a list of tuples like this one:

{% set typeLabels = [
    ('type1', 'Label for type 1'),
    ('type2', 'Label for type 2'),
    ('type3', 'Label for type 3')
] %}

I use a list and not a dict because the order is important (I also use the list elsewhere to generate a listbox).

Then I need to do lookups like this one:

{{ dict(typeLabels)[someType] }}

which works fine if you do it inside Python, but in Jinja it doesn't work.

How can I do this in Jinja?

War es hilfreich?

Lösung

Well, since there's no answers I'll post my solution based on the suggestions.

First you have to add collections.OrderedDict to the Jinja environment since Jinja doesn't know about it:

JINJA_ENV = jinja2.Environment( . . . )
JINJA_ENV.globals['OrderedDict'] = collections.OrderedDict

And then in the template:

{% set typeLabels = OrderedDict([
    ('type1', 'Label for type 1'),
    ('type2', 'Label for type 2'),
    ('type3', 'Label for type 3')
]) %}

So now you can access the dictionary normally:

{{ typeLabels[someType] }}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top