Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

templates

go

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.

like image 760
Laserallan Avatar asked May 25 '12 00:05

Laserallan


1 Answers

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.

like image 54
Sonia Avatar answered Oct 20 '22 06:10

Sonia