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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With