I'm trying to write a string looking like this using go's template system: (p1, p2, p3), where p1, p2, ... comes from an array in the program. My problem is how to place the comma properly for the last (or the first) element.
My non working version that outputs (p1, p2, p3, ) looks like this:
package main
import "text/template"
import "os"
func main() {
ip := []string{"p1", "p2", "p3"}
temp := template.New("myTemplate")
temp,_ = temp.Parse(paramList)
temp.Execute(os.Stdout, ip)
}
const paramList =
`{{ $i := . }}({{ range $i }}{{ . }}, {{end}})`
My best clue so far is found here http://golang.org/pkg/text/template/ in the following statement:
If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:
$index, $element := pipeline
in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses. where it's suggested that the index
This suggests that it's possible to get hold of the index in the iteration but I just can't figure out what is meant with the range declaring two variables and where in the template those variables are supposed to be declared.