简体   繁体   English

您如何在Jinja2中对列表进行排序?

[英]How do you sort a list in Jinja2?

I am trying to do this: 我正在尝试这样做:

 {% for movie in movie_list | sort(movie.rating) %}

But that's not right...the documentation is vague...how do you do this in Jinja2? 但这不对...文档模糊不清...您如何在Jinja2中做到这一点?

As of version 2.6, Jinja2's built-in sort filter allows you to specify an attribute to sort by: 从2.6版开始,Jinja2的内置排序过滤器允许您指定一个属性以进行排序:

{% for movie in movie_list|sort(attribute='rating') %}

See http://jinja.pocoo.org/docs/templates/#sort 参见http://jinja.pocoo.org/docs/templates/#sort

If you want to sort in ascending order 如果要按升序排序

{% for movie in movie_list|sort(attribute='rating') %}

If you want to sort in descending order 如果要按降序排序

{% for movie in movie_list|sort(attribute='rating', reverse = True) %}

Usually we sort the list before giving it to Jinja2. 通常,我们在将列表提供给Jinja2之前对其进行排序。 There's no way to specify a key in Jinja's sort filter. 无法在Jinja的sort过滤器中指定键。

However, you can always try {% for movie in movie_list|sort %} . 但是,您始终可以尝试{% for movie in movie_list|sort %} That's the syntax. 这就是语法。 You don't get to provide any sort of key information for the sorting. 您不会为排序提供任何关键信息。

You can also try and write a custom filter for this. 您也可以尝试为此编写一个自定义过滤器。 Seems silly when you can sort before giving the data to Jinja2. 在将数据提供给Jinja2之前可以进行排序时似乎很愚蠢。

If movie_list is a list of objects, then you can define the various comparison methods ( __lt__ , __gt__ , etc.) for the class of those objects. 如果movie_list是对象列表, __gt__这些对象的类定义各种比较方法( __lt____gt__等)。

If movie_list is a list of tuples or lists, the rating must be first. 如果movie_list是元组或列表的列表,则等级必须为第一。 Or you'll have to do the sorting outside Jinja2. 否则,您将不得不在Jinja2之外进行排序。

If movie_list is a list of dictionaries, then you can use dictsort , which does accept a key specification for the sorting. 如果movie_list是词典列表,则可以使用dictsort ,它确实接受用于排序的键规范。 Read this: http://jinja.pocoo.org/2/documentation/templates#dictsort for an example. 阅读此示例: http : //jinja.pocoo.org/2/documentation/templates#dictsort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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