user206545
user206545

Reputation:

Sorting columns in table created in Flask

I've written a Flask application that displays some data in the form of a table with multiple columns. Each column has a header cell. Clicking in the column's header cell, I want to sort the column's contents either up or down depending upon its previous state. Since click detection occurs in the browser, it seems I need to create a javascript click handler that somehow needs to notify the application on the server which would then sort the table and redisplay it.

Not being a javascript programmer, I don't know how to make that connection. How can I do this? Is there a simpler way to do what I want?

Upvotes: 2

Views: 3640

Answers (1)

bgse
bgse

Reputation: 8587

No JavaScript is needed for this, you can give a dict with the sorting parameters when rendering the template. Not a complete code, but this should get the idea across:

sortparams = { 'sortby': 'column_name', 'sortdir': 'asc' }

...

return render_template('example.html', sortparams=sortparams)

Depending on the settings, display the appropriate table column header in the template, and call the same view when the user clicks the header, with changed sort params.

If the user clicks a column header of currently sorted column, reset the sorting, along these lines:

{% if sortparams.sortby == 'column_name' %}
<a href="url_for('sameroute', sortby=None)">Column_Name, sorted by</a>
{% endif %}

If no sort parameters was supplied when the view was called, initialize it with default values that indicate 'no sorting' when you render the template.

Write a convenience function to extract your sort parameters, and you can re-use that in every route that needs sorting.

This approach obviously works best if you also have your table fully generated, and do not have to repeat for dozens of columns manually.

Upvotes: 3

Related Questions