根据数据库中的元素数量在模板中创建"x"数量的 html 元素

  • 本文关键字:元素 html 创建 数据库 go
  • 更新时间 :
  • 英文 :


我需要创建一个html页面,显示所有的论坛"存在于我的.html文件中的数据库中。例子:

<body>
{{with index . 0}}
<a href="/sID={{.Id}}">{{.Name}}<br></a>{{.Descr}}</td>
{{end}}
{{with index . 1}}
<a href="/sID={{.Id}}">{{.Name}}<br></a>{{.Descr}}
{{end}}
</body>
func index(w http.ResponseWriter, r *http.Request) {
forums := GetForumsFromDB() // return a slice of type Forum from the db
tpl.ExecuteTemplate(w, "index.html", forums)
}
type Forum struct {
Id    int
Name  string
Descr string
}

但在这种情况下,我需要已经知道有多少论坛是在数据库时编写。html文件。我该如何处理这个问题?我应该将html与切片一起传递到模板中吗?我应该使用一个方法的论坛,返回html的每个论坛?

使用range:

{{range .}}
<a href="/sID={{.Id}}">{{.Name}}<br></a>{{.Descr}}
{{end}}

最新更新