Home > front end >  hugo how to sort tags and categories in terms.html
hugo how to sort tags and categories in terms.html

Time:03-22

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 ?

CodePudding user response:

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 }}

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

CodePudding user response:

Less clutter:

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

Docs: https://gohugo.io/templates/lists/#by-title

  • Related