首页 > 文章列表 > 根据我在数据库中的元素数量,在模板中动态生成相同数量的html元素

根据我在数据库中的元素数量,在模板中动态生成相同数量的html元素

364 2024-02-11
问题内容

我需要创建一个 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}}