简体   繁体   中英

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. 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 .

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