I need to access some arbitrary element in array in template.
I have a function that returns an array of 3 elements and I want to access only the second element. How do I do that?
the template:
test start
{{ service "mongodb" }}
test end
results in:
test start
[0xc208062de0 0xc208062d80 0xc208062e40]
test end
I think predefined global function index
could help here, documentation from package template
index
Returns the result of indexing its first argument by the
following arguments. Thus "index x 1 2 3" is, in Go syntax,
x[1][2][3]. Each indexed item must be a map, slice, or array.
Here is an example;
package main
import (
"log"
"os"
"text/template"
)
func returnArray(dummy string) []int {
return []int{11, 22, 33}
}
func main() {
funcMap := template.FuncMap{
"myFunc": returnArray,
}
const templateText = `
Output 0: {{myFunc "abc"}}
Output 1: {{index (myFunc "abc") 0}}
Output 2: {{index (myFunc "abc") 1}}
Output 3: {{index (myFunc "abc") 2}}
`
tmpl, err := template.New("myFuncTest").Funcs(funcMap).Parse(templateText)
if err != nil {
log.Fatalf("parsing: %s", err)
}
err = tmpl.Execute(os.Stdout, "")
if err != nil {
log.Fatalf("execution: %s", err)
}
}
Output
Output 0: [11 22 33]
Output 1: 11
Output 2: 22
Output 3: 33