문제

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?

도움이 되었습니까?

해결책

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] }}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top