[英]Sort list of objects with Jinja2 and Flask depending the field pressed
I have a model in Flask called Dog, with the parameters Name, Breed and Age. 我在Flask中有一个名为Dog的模型,其中包含参数Name,Breed和Age。 Through Jinja2 I show them in a template as follow:
通过Jinja2,我在模板中显示如下:
<table>
<tr>
<td>Name</td>
<td>Breed</td>
<td>Age</td>
</tr>
{% for dog in dogs_list %}
<tr>
<td>{{ dog.name }}</td>
<td>{{ dog.breed }}</td>
<td>{{ dog.age }}</td>
</tr>
{% endfor %}
</table>
My idea is, if the user press Name, the table show the objects sorted by Name. 我的想法是,如果用户按名称,该表将显示按名称排序的对象。 The same with Breed and Age.
与品种和年龄相同。 There is a filter in Jinja to order by a parameter, for example "name":
Jinja中有一个按参数排序的过滤器,例如“name”:
{% for dog in dogs_list|sort(attribute='name') %}
But I do not want to put a fixed attribute, it should change to "breed" or "age". 但我不想提出一个固定的属性,它应该改为“繁殖”或“年龄”。 Can I do it just with Jinja2?
我可以用Jinja2做到吗? Should I use also Flask?
我也应该使用Flask吗? Can I set values in Jinja2 with JavaScript?
我可以用JavaScript在Jinja2中设置值吗?
Thanks! 谢谢!
The attribute does not need to be a fixed string, it can be a request parameter too: 该属性不需要是固定字符串,它也可以是请求参数:
{% set sort_on = request.args.sort_on|default('name') %}
{% for dog in dogs_list|sort(attribute=sort_on) %}
This looks for a GET parameter sort_on
(defaulting to 'name'
), then uses that value to sort the dogs_list
. 这将查找GET参数
sort_on
(默认为'name'
),然后使用该值对dogs_list
进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.