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

我想做这样的事情:

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

但模板未按预期呈现。我怎样才能解决这个问题?


海绵宝宝撒
浏览 110回答 2
2回答

斯蒂芬大帝

模板包不直接支持这一点。创建一个返回整数值切片的模板函数:var funcs = template.FuncMap{&nbsp; &nbsp; "intRange": func(start, end int) []int {&nbsp; &nbsp; &nbsp; &nbsp; n := end - start + 1&nbsp; &nbsp; &nbsp; &nbsp; result := make([]int, n)&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < n; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result[i] = start + i&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return result&nbsp; &nbsp; },}像这样使用它:t := template.Must(template.New("").Funcs(funcs).Parse(`{{range $y := intRange .minYear .maxYear}}&nbsp; &nbsp;<option value="y"> {{$y}}</option>{{end}}`))err := t.Execute(os.Stdout, map[string]int{"minYear": 1961, "maxYear": 1981})if err != nil {&nbsp; &nbsp; // handle error}在 Go 游乐场上运行它。

互换的青春

您可以在模板中使用 sprig 库:https://github.com/Masterminds/sprig
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go