Karlom
Karlom

Reputation: 14834

How to iterate over a range of numbers in golang template?

I'd like to do something like this:

  {{range $y := .minYear    .maxYear}}                                                                                                
      <option value="y"> {{$y}}</option>                                                                                                
  {{end}}

But the template is not rendered as expected. How can I fix this?

Upvotes: 0

Views: 5293

Answers (2)

Burak Serdar
Burak Serdar

Reputation: 51467

You can use the sprig library in your templates:

https://github.com/Masterminds/sprig

Upvotes: 0

Thundercat
Thundercat

Reputation: 120931

The template package does not support this directly. Create a template function that returns a slice of the integer values:

var funcs = template.FuncMap{
    "intRange": func(start, end int) []int {
        n := end - start + 1
        result := make([]int, n)
        for i := 0; i < n; i++ {
            result[i] = start + i
        }
        return result
    },
}

Use it like this:

t := template.Must(template.New("").Funcs(funcs).Parse(`{{range $y := intRange .minYear .maxYear}}
   <option value="y"> {{$y}}</option>{{end}}`))

err := t.Execute(os.Stdout, map[string]int{"minYear": 1961, "maxYear": 1981})
if err != nil {
    // handle error
}

Run it on the Go playground.

Upvotes: 2

Related Questions