Desired Result
I wanted the tags on this site (which was created with Zola, an excellent static site generator written in Rust) to be sorted by number of tagged articles, not alphabetically. The result can be seen on the /tags page, and looks like this:
Process
To accomplish this, you will need to edit your site’s theme.
- Open
templates/tags/list.html
or similar. There should be a directory for each type of taxonomy intemplates/
. - Inside
list.html
, find the for loop that iterates overterms
. It should look something like this:
{% if terms %}
<ul>
{% for term in terms %}
<li><a href="{{ term.permalink | safe }}">{{ term.name }}</a> ({{ term.pages | length }})</li>
{% endfor %}
</ul>
{% endif %}
- Add a sort filter with attribute set to
"pages"
(one of the available fields for each taxonomy) to the opening line of the for loop:
{% for term in terms | sort(attribute="pages") %}
Now it should look like this:
The tags are sorted, but they are backwards.
As the documentation says, the sort
filter always sorts items in ascending order.
Luckily, there is also the reverse
filter.
- Change the opening line of the for loop to the following:
{% for term in terms | sort(attribute="pages") | reverse %}
Conclusion
That’s it. Everything should work as intended now with the most commonly used tags at the top of the list.
Comments