Iterating a range of integers in Go templates

huangapple go评论151阅读模式
英文:

Iterating a range of integers in Go templates

问题

我正在尝试在模板中进行分页的迭代,但似乎没有办法进行 for 循环迭代。

我想要像这样进行迭代:

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

有什么建议吗?谢谢!

英文:

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

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

I want to do something like this

  1. {{range $i := 1 .. 10}}
  2. &lt;div&gt;{{$i}}&lt;/div&gt;
  3. {{end}}

Any advice? Thanks!

答案1

得分: 11

对于最少的工作量,你可以使用包github.com/bradfitz/iter来实现。它提供了一个名为N的函数,你可以像这样使用它:

  1. {{range $i, $_ := N 10}}
  2. &lt;div&gt;{{$i}}&lt;/div&gt;
  3. {{end}}

使用模板的Funcs方法来添加函数N,像这样:

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

对于1..m而不是0..m,使用N m+1并忽略0

  1. {{range $i, $_ := N 11}}
  2. {{if $i}}
  3. &lt;div&gt;{{$i}}&lt;/div&gt;
  4. {{end}}
  5. {{end}}

当然,你也可以完全不同地解决这个问题。只需定义一个接受两个参数并创建整数流的自定义函数,例如(play):

  1. func N(start, end int) (stream chan int) {
  2. stream = make(chan int)
  3. go func() {
  4. for i := start; i <= end; i++ {
  5. stream <- i
  6. }
  7. close(stream)
  8. }()
  9. return
  10. }
  11. templ := `{{range $i := N 1 10}}
  12. &lt;div&gt;{{$i}}&lt;/div&gt;
  13. {{end}}`
  14. t := template.New("foo").Funcs(template.FuncMap{"N": N})
英文:

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:

  1. {{range $i, $_ := N 10}}
  2. &lt;div&gt;{{$i}}&lt;/div&gt;
  3. {{end}}

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

  1. myTemplate.Funcs(template.FuncMap{&quot;N&quot;: iter.N})

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

  1. {{range $i, $_ := N 11}}
  2. {{if $i}}
  3. &lt;div&gt;{{$i}}&lt;/div&gt;
  4. {{end}}
  5. {{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):

  1. func N(start, end int) (stream chan int) {
  2. stream = make(chan int)
  3. go func() {
  4. for i := start; i &lt;= end; i++ {
  5. stream &lt;- i
  6. }
  7. close(stream)
  8. }()
  9. return
  10. }
  11. templ := `{{range $i := N 1 10}}
  12. &lt;div&gt;{{$i}}&lt;/div&gt;
  13. {{end}}`
  14. t := template.New(&quot;foo&quot;).Funcs(template.FuncMap{&quot;N&quot;: N})

huangapple
  • 本文由 发表于 2014年3月28日 20:55:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/22713500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定