Profile Picture

Assorted tech

Hi, my name is Spencer. I'm a CS graduate focused on systems programming, Linux, and low-complexity design. Other interests: metal, hiking, guitar, rationality.

feed | contact

Sort Tags by Number of Tagged Posts in Zola

Calendar icon October 8, 2020

Clock icon 2 min read

Folder icon #zola #staticsite #blog #webdev #tera in tech

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:

Sorted Tag List

Process

To accomplish this, you will need to edit your site’s theme.

  1. Open templates/tags/list.html or similar. There should be a directory for each type of taxonomy in templates/.
  2. Inside list.html, find the for loop that iterates over terms. 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 %}
  1. 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:

Backwards Sorted Tag List

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.

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