[SOLVED] How can I join two strings in go templates?

Issue

I found this documentation to join two strings, but this doesn’t work inside go templates.

Is there a way to join strings inside a go template?

Solution

Write a function to join the strings and add it to the template func map:

func join(sep string, s ...string) string {
    return strings.Join(s, sep)
}

Add the function to template before parsing:

t, err := template.New(name).Funcs(template.FuncMap{"join": join}).Parse(text)

Use it in the template like this:

{{$x := join ", " "hello" "world"}}

playground example

I assign to variable $x to show how use the function result in a template expression. The result can be used directly as an argument to another function without assigning to a variable.

Here’s a version of the function that works with slices instead of variadic arguments:

func join(sep string, s []string) string {
    return strings.Join(s, sep)
}

Use it like this where . is a slice:

{{$x := join ", " .}}  

playground example.

If your goal is to join two strings directly do the output, then then use {{a}}sep{{b}} where a and b are the strings and sep is the separator.

Use range to join a slice to the output. Here’s an example that joins slice . with separator ", ".:

{{range $i, $v := .}}{{if $i}}, {{end}}{{$v}}{{end}}

playground example.

Answered By – Bayta Darell

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *