简体   繁体   中英

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) %}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM