0

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?

Karlom
  • 13,323
  • 27
  • 72
  • 116
  • 1
    Related / possible duplicate: [Golang code to repeat an html code n times](https://stackoverflow.com/questions/46112679/golang-code-to-repeat-an-html-code-n-times/46112802#46112802) – icza Sep 02 '19 at 20:07

2 Answers2

2

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
0

You can use the sprig library in your templates:

https://github.com/Masterminds/sprig

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59