Reputation: 9641
I want to render a simple pagination list in a Go html/template. Go templates only support for loops over ranges ({{range x}}{{.}}{{end}}
) - I only have a simple int
. Is there a more elegant way than creating a fake slice, map, or chan of the right size? All of that seems a bit heavy handed just for outputting something N times.
Upvotes: 3
Views: 813
Reputation: 17413
You can register a function which produces a slice:
package main
import (
"os"
"text/template"
)
func main() {
funcMap := template.FuncMap{
"slice": func(i int) []int { return make([]int, i) },
}
tmpl := `{{$x := .}}{{range slice 10}}<p>{{$x}}</p>{{end}}`
t, _ := template.New("template").Funcs(funcMap).Parse(tmpl)
t.Execute(os.Stdout, "42")
}
Check it in playground
Upvotes: 3