使用Jinja2和Flask根据按下的字段排序对象列表 [英] Sort list of objects with Jinja2 and Flask depending the field pressed
问题描述
< table>
< tr>
< td>名称< / td>
< td>品种< / td>
< td>年龄< / td>
< / tr>
{%dog for dogs_list%}
< tr>
< td> {{dog.name}}< / td>
< td> {{dog.breed}}< / td>
< td> {{dog.age}}< / td>
< / tr>
{%endfor%}
< / table>
我的想法是,如果用户按下Name,则表格显示按Name排序的对象。同品种和年龄一样。 Jinja中有一个过滤器可以通过一个参数进行排序,例如name:
$ p $ (attribute ='name')%}
但是我不想把一个固定的属性应改为品种或年龄。我可以用Jinja2吗?我也应该使用烧瓶?我可以使用JavaScript在Jinja2中设置值吗?
谢谢!
属性不需要是固定的字符串,也可以是请求参数:
{%set sort_on = request .args.sort_on | default('name')%}
{%for dog in dogs_list | sort(attribute = sort_on)%}
这会查找GET参数 sort_on
(默认为'name'
),然后使用该值来排序 dogs_list
。
I have a model in Flask called Dog, with the parameters Name, Breed and Age. Through Jinja2 I show them in a template as follow:
<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":
{% 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? Should I use also Flask? Can I set values in Jinja2 with JavaScript?
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
.
这篇关于使用Jinja2和Flask根据按下的字段排序对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!