根据我在数据库中有多少个元素,创建“x”个HTML元素的模板。

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

Create "x" amount of html elements in template based on how many elements I have in DB

问题

我需要创建一个 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() // 从数据库返回一个 Forum 类型的切片
tpl.ExecuteTemplate(w, "index.html", forums)
}

type Forum struct {
	Id    int
	Name  string
	Descr string
}

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

英文:

I need to create an html page that display all the "forums" present in the database in my .html file.
Example:

&lt;body&gt;
{{with index . 0}}
  &lt;a href=&quot;/sID={{.Id}}&quot;&gt;{{.Name}}&lt;br&gt;&lt;/a&gt;{{.Descr}}&lt;/td&gt;
{{end}}

{{with index . 1}}
  &lt;a href=&quot;/sID={{.Id}}&quot;&gt;{{.Name}}&lt;br&gt;&lt;/a&gt;{{.Descr}}
{{end}}
&lt;/body&gt;

func index(w http.ResponseWriter, r *http.Request) {
forums := GetForumsFromDB() // return a slice of type Forum from the db
tpl.ExecuteTemplate(w, &quot;index.html&quot;, forums)
}

type Forum struct {
	Id    int
	Name  string
	Descr string
}

But in this case I need to already know how many forums are there in the db when writing the .html file. How should I approach this? Should I pass the html into the template together with my slice? Should I use a method of Forum that return the html for every forum?

答案1

得分: 1

使用range

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

使用range函数可以遍历一个集合,并在模板中重复执行指定的代码块。在上述示例中,.表示当前迭代的元素,可以通过.来访问元素的属性。在这个例子中,我们使用range来遍历一个集合,并为每个元素生成一个包含链接和描述的HTML代码块。

英文:

Use range:

{{range .}}
  &lt;a href=&quot;/sID={{.Id}}&quot;&gt;{{.Name}}&lt;br&gt;&lt;/a&gt;{{.Descr}}
{{end}}

huangapple
  • 本文由 发表于 2023年1月16日 01:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75126959.html
匿名

发表评论

匿名网友

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

确定