Tom
Tom

Reputation: 9643

How do you sort a list in Jinja2 by X element?

I'm looking at the answer in this SO thread but my list doesn't have an attribute. I'm trying to sort by unique string in the second list element. This doesn't seem to work:

{% for item in whole_list | sort(whole_list.1) %}

Upvotes: 0

Views: 2460

Answers (1)

bereal
bereal

Reputation: 34282

It's not currently documented, but Jinja2's sort filter also accepts an index for attribute transparently. So the same syntax will work:

{% for item in whole_list | sort(attribute=1) %}
anything with item
{% endfor %}

That works because in general Environment.getitem() is used for both attributes and collection items resolution.

Upvotes: 2

Related Questions