Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Templates Go模板:在索引上循环_Templates_Go_Range - Fatal编程技术网

Templates Go模板:在索引上循环

Templates Go模板:在索引上循环,templates,go,range,Templates,Go,Range,我想在Go html/模板中呈现一个简单的分页列表。Go模板只支持范围上的循环({{range x}}{{{.}}{{end}})-我只有一个简单的int。有没有比创建一个大小合适的假切片、地图或成龙更优雅的方法?所有这一切似乎都有点过于繁重,仅仅是为了输出N次的内容。您可以注册一个生成切片的函数: package main import ( "os" "text/template" ) func main() { funcMap := template.FuncMap{

我想在Go html/模板中呈现一个简单的分页列表。Go模板只支持范围上的循环(
{{range x}}{{{.}}{{end}}
)-我只有一个简单的
int
。有没有比创建一个大小合适的假切片、地图或成龙更优雅的方法?所有这一切似乎都有点过于繁重,仅仅是为了输出N次的内容。

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

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")

}
主程序包
进口(
“操作系统”
“文本/模板”
)
func main(){
funcMap:=模板。funcMap{
“slice”:func(i int)[]int{返回make([]int,i)},
}
tmpl:=`{{$x:=.}{{range slice 10}}{{$x}

{{end}` t、 =template.New(“template”).Funcs(funcMap).Parse(tmpl) t、 执行(os.Stdout,“42”) }

检查一下

是的,但这仍然需要创建一个新的片(可能会使用相当多的内存),以实现一个简单的1..n循环。这似乎很奇怪。