.Pages custom sort filter

I have a “country” taxonomy that’s identified by the ISO country code. I also have a json file that maps that country code to their name.

In the list template for the taxonomy, I’d like to list the countries according to their name. Is there some sort of custom algorithm? I’d like to iterate over the pages, grab their name from the {{.Title}} and then sort that. I’ve tried to build a dictionary that maps the name to the page but I don’t see how I can get back the keys to sort them. I could create a page per country, and adding the front matter there but if I can make it generic that would be easier.

config.toml

[taxonomies]
country = 'countries'

data/countries.toml

us = 'Unites States'
fr = 'France'
de = 'Germany'
layouts/_default/terms.html
{{ define "main" }}
  <h1>{{ .Title }}</h1>
  {{ .Content }}

  {{/* Build slice of maps. */}}
  {{ $p := slice }}
  {{ range .Pages }}
    {{ $countryName := index site.Data.countries .Data.Term }}
    {{ if not $countryName }}
      {{ errorf "Unable to find the country code %q in the countries data file." .Data.Term  }}
    {{ end }}
    {{ $p = $p | append (dict "countryName" $countryName "page" . ) }}
  {{ end }}

  {{/* Iterate through slice of maps, sorting by country name. */}}
  {{ range sort $p "countryName" }}
    <h2><a href="{{ .page.RelPermalink }}">{{ .countryName }}</a> ({{ .page.Data.Term }})</h2>
  {{ end }}

{{ end }}

layouts/_default/term.html
{{ define "main" }}
  <h1>{{ index site.Data.countries .Data.Term }}</h1>
  {{ .Content }}
  {{ range .Pages }}
    <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
  {{ end }}
{{ end }}

layouts/_default/single.html
{{ define "main" }}
  <h1>{{ .Title }}</h1>

  {{ with .GetTerms "countries" }}
    <p>Countries:
      {{ range . }}
        <a href="{{ .RelPermalink }}">{{ index site.Data.countries .Data.Term }}</a>
      {{ end }}
    </p>
  {{ end }}

  {{ .Content }}
{{ end }}

1 Like

Thanks for yet another spot on answer, Joe. The page is now live: Stéphane Nicoll | Country

1 Like

Nice!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.