Easier way to replace array with array?

You often need to replace a substring with another substring in a string variable. And almost as often you need to do this operation sevarl times.

From this I would have expected a consecutive string replace to be quite straightforward in a Go template. But it does’t seem to be the case.

At least I didn’t manage to find an easy solution for chaining this {{ replace .Title "-" " " }}

And the following howegrown desperado hacks didn’t work:

{{ replace .Title "aa" "æ" | replace "oe" "ø" | replace "aa" "å" }}

{{ replace .Title ["-", "aa", "oe", "aa"] [" ", "æ", "ø", "å"] }}

{{ .Title | replace "-" " " | replace "aa" "æ" | replace "oe" "ø" | replace "aa" "å" }}

After quite some search this post about maps and dict got me on track.

So now this code does the job and turn my non-scandinavian urls into words with special scandinavian letters:

{{ $pairs := (dict "-" " " "ae" "æ" "oe" "ø" "aa" "å") }}
{{ $.Scratch.Set "specialTitle" .Title }}
{{ range $key, $val := $pairs }}
    {{ $.Scratch.Set "specialTitle" (replace ($.Scratch.Get "specialTitle") $key $val) }}
{{ end }}
{{ $.Scratch.Get  "specialTitle" }}

But it seems like overkill for a rather simple task. Or have I missed the smart way?

If not: How about making use of the replacer class in Go and offer replacer-functionality in Go templates?

1 Like

Why do you this?

I use utf-8 codings ans all works fine with German umlauts. No need to use ä etc.
My Linux / Raspian is set to utf-8 codepages, Filezilla is set to utf-8 - and no problems more!