Golang templates: how to define an array in a variable?

What would be the correct syntax for defining an array variable inside the go template? (here is the HTML template). Here is what I tried:

{{define "template"}} {{ $x:=[]int{0,1,2} }}{{$x[0]}} {{end}} 

The error log says: unexpected "[" in command

Thanks.

+7
variables arrays go templates
source share
2 answers

There is no built-in way to do what you want to achieve. See arguments for what you can do with arguments and the pipeline.

But you can easily define your own function to achieve your goal:

 package main import ( "html/template" "os" ) func main() { tmpl := ` {{ $slice := mkSlice "a" 5 "b" }} {{ range $slice }} {{ . }} {{ end }} ` funcMap := map[string]interface{}{"mkSlice": mkSlice} t := template.New("demo").Funcs(template.FuncMap(funcMap)) template.Must(t.Parse(tmpl)) t.ExecuteTemplate(os.Stdout, "demo", nil) } func mkSlice(args ...interface{}) []interface{} { return args } 

Playground

+7
source share

map or array not supported, but I pass the map or array variable from the controller to the template, then use {{index .Varible KEY}} to get the value of map or array to forward the operation. wish it could help you.

+1
source share

All Articles