Iterating a range of integers in Go templates

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

Iterating a range of integers in Go templates

问题

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

我想要像这样进行迭代:

{{range $i := 1 .. 10}}
    <div>{{$i}}</div>
{{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

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

I want to do something like this

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

Any advice? Thanks!

答案1

得分: 11

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

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

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

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

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

{{range $i, $_ := N 11}}
    {{if $i}}
        &lt;div&gt;{{$i}}&lt;/div&gt;
    {{end}}
{{end}}

当然,你也可以完全不同地解决这个问题。只需定义一个接受两个参数并创建整数流的自定义函数,例如(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}}
            &lt;div&gt;{{$i}}&lt;/div&gt;
          {{end}}`

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:

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

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

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

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

{{range $i, $_ := N 11}}
    {{if $i}}
        &lt;div&gt;{{$i}}&lt;/div&gt;
    {{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 &lt;= end; i++ {
			stream &lt;- i
		}
		close(stream)
	}()
	return
}

templ := `{{range $i := N 1 10}}
			&lt;div&gt;{{$i}}&lt;/div&gt;
	  {{end}}`

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:

确定