Special treatment for the last element of the range in Google Go templates

I am trying to write a line similar to this using the go template system: (p1, p2, p3), where p1, p2, ... comes from an array in the program. My problem is how to correctly place a comma for the last (or first) element.

My non-working version, which 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 tip is found here http://golang.org/pkg/text/template/ in the following statement:

If the range action initializes the variable, the variable is set to consecutive iteration elements. In addition, a range can declare two variables, separated by a comma:

 $index, $element := pipeline 

in this case, $ index and $ element are set to consecutive values ​​of the index of the array / slice or the key of the card and element, respectively. Note: if there is only one variable, an element is assigned to it; this is contrary to convention in the Go range offerings. where he suggested that the index

This suggests that you can get the index in the iteration, but I just can’t understand what is meant by a range declaring two variables, and where in the template it is assumed that these variables should be declared.

+6
source share
1 answer

See this example from the go-nuts mailing list. One of the key points is that the if pattern is different from the Go if language. A template can test a value of zero, unlike the Go language, which requires a logical value. The magic is then {{if $index}},{{end}} , where $ index does not need a declaration other than its appearance in assignment.

+8
source

Source: https://habr.com/ru/post/916612/