Go模板:循环索引

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

Go Templates: looping over index

问题

我想在Go的html/template中渲染一个简单的分页列表。Go模板只支持通过范围进行循环({{range x}}{{.}}{{end}}) - 我只有一个简单的整数。有没有比创建一个大小合适的假切片、映射或通道更优雅的方法?所有这些方法似乎都有点过于繁琐,只是为了输出N次某个内容。

英文:

I want to render a simple pagination list in a Go html/template. Go templates only support for loops over ranges ({{range x}}{{.}}{{end}}) - I only have a simple int. Is there a more elegant way than creating a fake slice, map, or chan of the right size? All of that seems a bit heavy handed just for outputting something N times.

答案1

得分: 3

你可以注册一个生成切片的函数:

package main

import (
  "os"
  "text/template"
)

func main() {

	funcMap := template.FuncMap{
	  "slice": func(i int) []int { return make([]int, i) },
	}

	tmpl := `{{$x := .}}{{range slice 10}}<p>{{$x}}</p>{{end}}`
	t, _ := template.New("template").Funcs(funcMap).Parse(tmpl)
	t.Execute(os.Stdout, "42")

}

playground中查看。

英文:

You can register a function which produces a slice:

package main

import (
  &quot;os&quot;
  &quot;text/template&quot;
)

func main() {

	funcMap := template.FuncMap{
	  &quot;slice&quot;: func(i int) []int { return make([]int, i) },
	}

	tmpl := `{{$x := .}}{{range slice 10}}&lt;p&gt;{{$x}}&lt;/p&gt;{{end}}`
	t, _ := template.New(&quot;template&quot;).Funcs(funcMap).Parse(tmpl)
	t.Execute(os.Stdout, &quot;42&quot;)

}

Check it in playground

huangapple
  • 本文由 发表于 2014年5月2日 01:31:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/23413072.html
匿名

发表评论

匿名网友

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

确定