I have a slice/list of authors like ["Thomas Mann", "Günther Grass", "William Shakesspeare" … ].
To sort them, I currently do something like this:
{{ $namesReversed := slice}}
{{ range $names }}
{{ $namesReversed = $namesReversed | append (replaceRE `(.*) (.*)$` `$2 $1` .Name) }}
{{ end }}
{{/* The slice is now ["Mann Thomas", "Grass Günther", "Shakesspeare William"…]
{{ range (sort $namesReversed)}}
{{ $originalName := replaceRE `(.*?) (.*)$` `$2 $1` .Name
{{ end }}
That does not really sort the original slice, but it allows me to get the original names in order. Is there a better way to do that?
The code assumes that the part in a name after the last space character is the last name. It then puts that in front using replaceRE. To re-build the original name, nearly the same regular expression is used – this time with a non-greedy first part to isolate everything upto the first space.
Another approach is that creating author pages for each author, and correct the name for those authors, then you’re able to sort it like pages directly. For example,
Firstly, append the authors into the taxonomies in configuration.
[taxonomies]
authors = "authors"
# ...
And then create author pages to fix the author names and add any parameters you want.
// content/authors/günther-grass/_index.md
---
title: Grass Günther
first_name: Grass
last_name: Günther
---
// content/authors/thomas-mann/_index.md
---
title: Mann Thomas
first_name: Mann
last_name: Thomas
---
// content/authors/william-shakesspeare/_index.md
---
title: Shakesspeare William
first_name: Shakesspeare
last_name: William
---
Sample page
---
title: Hello world.
authors:
- Thomas Mann
- Günther Grass
- William Shakesspeare
---
Template:
{{- $authors := .GetTerms "authors" }}
{{- range .Params.authors }}
{{- . | warnf "[original] : %v" }}
{{- end }}
{{ warnf "sort by title" }}
{{- range sort $authors "Title" }}
{{- .Title | warnf "[title] : %v" }}
{{- end }}
{{ warnf "sort by first name" }}
{{- range sort $authors "Params.first_name" }}
{{- .Title | warnf "[first_name] : %v" }}
{{- end }}
{{ warnf "sort by last name" }}
{{- range sort $authors "Params.last_name" }}
{{- .Title | warnf "[last_name] : %v" }}
{{- end }}
Result:
WARN [original] : Thomas Mann
WARN [original] : Günther Grass
WARN [original] : William Shakesspeare
WARN sort by title
WARN [title] : Grass Günther
WARN [title] : Mann Thomas
WARN [title] : Shakesspeare William
WARN sort by first name
WARN [first_name] : Grass Günther
WARN [first_name] : Mann Thomas
WARN [first_name] : Shakesspeare William
WARN sort by last name
WARN [last_name] : Grass Günther
WARN [last_name] : Mann Thomas
WARN [last_name] : Shakesspeare William
I agree, that is probably feasible. OTOH, it’s not DRY.
You are obviously right. But I was simply following the sample stuff in the documentation with the Actor Taxonomy. It’s Marlon Brando there – neither Brando Marlon nor firstname: Marlon, lastname: Brando.