I'm trying to do an iteration in the template for pagination but there doesn't seem to be a way to do a for iteration.
Instead of
{{range $i, $e := .aSlice}}
I want to do something like this
{{range $i := 1 .. 10}}
<div>{{$i}}</div>
{{end}}
Any advice? Thanks!
For the least amount of work you can use the package github.com/bradfitz/iter for that.
It provides a function N
which you can use like this:
{{range $i, $_ := N 10}}
<div>{{$i}}</div>
{{end}}
Use the Funcs
method on the template to add the function N
like this:
myTemplate.Funcs(template.FuncMap{"N": iter.N})
For 1..m
instead of 0..m
use N m+1
and ignore the 0
:
{{range $i, $_ := N 11}}
{{if $i}}
<div>{{$i}}</div>
{{end}}
{{end}}
Of course you can solve this completely different. Just define your own function that takes two parameters and creates a stream of integers for example (play):
func N(start, end int) (stream chan int) {
stream = make(chan int)
go func() {
for i := start; i <= end; i++ {
stream <- i
}
close(stream)
}()
return
}
templ := `{{range $i := N 1 10}}
<div>{{$i}}</div>
{{end}}`
t := template.New("foo").Funcs(template.FuncMap{"N": N})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With