Home > Back-end >  How can I join strings in Go template without template functions?
How can I join strings in Go template without template functions?

Time:09-17

I have a string slice, like x := []string{a,b,c}, and eventually I want it to be like a "/" b "/" c.

The problem I'm trying to deal with is coming from the Go template.
I want to have a solution in Go template.

The following is my current solution, but it's obviously ugly.

res := {{range item := .x}}item "/"{{end}}
res = res[:len(res)-1]

If you have better approaches, appreciate it!

CodePudding user response:

Use the following code to join a slice with /:

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

Run the example on the playground.

  • Related