10

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!

1 Answer 1

11

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})
2
  • Thanks! I'll go with the second option. It's weird though that this is not provided in the standard library.
    – VoidMain
    Mar 28, 2014 at 15:29
  • If you really think this should be included you can always open a ticket here. However, go makes it really easy to use third party libraries, so the only major drawback I see is that I can't use these in examples on play.golang.org :)
    – nemo
    Mar 28, 2014 at 15:41

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.