Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating a range of integers in Go templates

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!

like image 337
VoidMain Avatar asked Mar 28 '14 12:03

VoidMain


1 Answers

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})
like image 68
nemo Avatar answered Oct 21 '22 14:10

nemo