dqyp50298 2014-03-28 12:55
浏览 45
已采纳

在Go模板中迭代整数范围

I'm trying to do an iteration in the template for pagination but there doesn't seem to be a way to do a for iteration.

Instead of

{{range $i, $e := .aSlice}}

I want to do something like this

{{range $i := 1 .. 10}}
    <div>{{$i}}</div>
{{end}}

Any advice? Thanks!

  • 写回答

1条回答 默认 最新

  • douliao8402 2014-03-28 15:16
    关注

    For the least amount of work you can use the package github.com/bradfitz/iter for that. It provides a function N which you can use like this:

    {{range $i, $_ := N 10}}
        <div>{{$i}}</div>
    {{end}}
    

    Use the Funcs method on the template to add the function N like this:

    myTemplate.Funcs(template.FuncMap{"N": iter.N})
    

    For 1..m instead of 0..m use N m+1 and ignore the 0:

    {{range $i, $_ := N 11}}
        {{if $i}}
            <div>{{$i}}</div>
        {{end}}
    {{end}}
    

    Of course you can solve this completely different. Just define your own function that takes two parameters and creates a stream of integers for example (play):

    func N(start, end int) (stream chan int) {
        stream = make(chan int)
        go func() {
            for i := start; i <= end; i++ {
                stream <- i
            }
            close(stream)
        }()
        return
    }
    
    templ := `{{range $i := N 1 10}}
                <div>{{$i}}</div>
          {{end}}`
    
    t := template.New("foo").Funcs(template.FuncMap{"N": N})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?