Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 740
Alvaro Garcia de la Villa Avatar asked Feb 24 '14 14:02

Alvaro Garcia de la Villa


1 Answers

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.

like image 75
Martijn Pieters Avatar answered Oct 03 '22 16:10

Martijn Pieters