I found this documentation tojoin two strings, but this doesn't work inside go templates.
Is there a way to join strings inside a go template?
5 Answers5
Write a function to join the strings and add it to the templatefunc 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"}}
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 ", " .}}
If your goal is to join two strings directly do the output, then then use{{a}}sep{{b}}
wherea
andb
are the strings andsep
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}}
Comments
Use a combination ofdelimit
andslice
, e.g.
{{ delimit (slice "foo" "bar" "buzz") ", " }}<!-- returns the string "foo, bar, buzz" -->
Originally from thegohugo docs
1 Comment
delimit
is not part of the defaulttemplate functionsHere is how I joined two strings in go template language (this is within a Helm template for Kubernetes). In this case I am creating a host name using go'sprintf
function:
host: {{ printf "%v%v" "my-super" ".apps.my.org" }}
Put in a%v
for each value.
The output is:
host: my-super.apps.my.org
You can put spaces between the%v
values, or commas, or whatever -- check with go's string format options for more, um, options!
2 Comments
In the template examplehttps://golang.org/src/text/template/example_test.go they show you how to do this.
In summary:
var funcs = template.FuncMap{"join": strings.Join}...masterTmpl, err := template.New("master").Funcs(funcs).Parse(master)
There's some other neat tricks in the example too.
Comments
Variable Overwrite Gotcha
In case anyone else is trying to 'join' potentially-empty strings with a separator, beware:=
vs=
. The latter is for updating a variable.
{{- $path := .Values.fileName -}}{{- if .Values.folder }}{{- $path = print .Values.folder "/" $path }}{{- end }}
Using$path := ..
inside the if will create a new variable scoped to the if statement.
Comments
Explore related questions
See similar questions with these tags.