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

如何在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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊