I need to only iterate over a loop once in my golang template, currently it is looping over all the keys but I want it to stop after a single iteration.
How can I do this?
{{range .Users}}
<div>
{{.Name}}
</div>
{{end}}
instead of range, give index
with an argument
{{index .Users 0}}
<div>
{{.Name}}
</div>
{{end}}
Two solutions; either check that your index is 0 when looping:
{{range $index, $element := . }}{{if eq $index 0 -}}
Item: {{$element}}
{{end}}{{end -}}
Or you could define a "first" function that takes a slice and truncates it to length 1.
{{range first .}}
Item: {{.}}
{{end}}
Here's complete code that demonstrates both, which you can also try on the playground.
package main
import (
"fmt"
"os"
"text/template"
)
var t = template.Must(template.New("x").Parse(
"[{{range $index, $element := . }}{{if eq $index 0 -}}{{$element}}{{end}}{{end -}}]"))
var funcs = map[string]interface{}{
"first": func(arg []string) []string {
if len(arg) > 0 {
return arg[:1]
}
return nil
},
}
var t2 = template.Must(template.New("x").Funcs(funcs).Parse(
"[{{range first . }}{{.}}{{end -}}]"))
func main() {
tmpls := []*template.Template{t, t2}
for i, t := range tmpls {
fmt.Println("TEMPLATE", i)
a := []string{"one", "two", "three"}
for j := 0; j < len(a); j++ {
fmt.Println("with input slice of length", j)
t.Execute(os.Stdout, a[:j])
fmt.Println()
}
fmt.Println()
}
}