Special case treatment for the last element of a range in Google Go's text templates
Asked Answered
C

1

9

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.

Cinematograph answered 25/5, 2012 at 0:30 Comment(0)
U
15

See this example from the go-nuts mailing list. One key to this trick is that a template if is different than a Go language if. A template can test for a value of zero, unlike the Go language that requires a boolean. The magic is then {{if $index}},{{end}} where $index needs no declaration other than its appearance in the assignment.

Unmoving answered 25/5, 2012 at 3:2 Comment(1)
Here is a working example for this: play.golang.org/p/KuRh55BHna8Toscana

© 2022 - 2024 — McMap. All rights reserved.