dongtuwu8548
2019-09-02 19:54
浏览 67
已采纳

如何在golang模板中迭代一系列数字?

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanquan1876 2019-09-02 20:05
    已采纳

    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.

    点赞 评论
  • douxian1939 2019-09-02 20:08

    You can use the sprig library in your templates:

    https://github.com/Masterminds/sprig

    点赞 评论

相关推荐 更多相似问题