sortingtagscategorieshugo

hugo how to sort tags and categories in terms.html


Following the documentation, I have my layouts/_default/terms.html template which looks like this:

{{ range .Pages }}
<li>
    <a href="{{ .Permalink }}">{{ .Title }}</a>
</li>
{{ end }}

My tags or categories (depending on if I'm on /tags/ or /categories/) list all the tags/categories but not in alphabetical order.

How to sort them ? I have tried to add the sort keyword like this {{ range sort .Pages }} but it doesn't work. Any idea how to sort them by .Title ?


Solution

  • You need to specify the property to sort on to the sort function. Since you're iterating over a list of tag pages, you probably want to use the titles of the pages (which are the tag names):

    {{ range (sort .Pages "Title") }}
    <li>
        <a href="{{ .Permalink }}">{{ .Title }}</a>
    </li>
    {{ end }}
    

    Similarly, if you want to sort tags passed as Params, you can do that like so:

    {{ range  (sort .Params.tags) }}
    <li class="tag-{{ . }}">
        <a href="{{ "tags/" | absLangURL }}{{ . | urlize }}">{{ . }}</a>
    </li>
    {{ end }}
    

    If you want the list to be in the opposite order, pass "desc" to the sort function as the third argument.