I need to create an html page that display all the "forums" present in the database in my .html file. Example:
<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
}
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?
CodePudding user response:
Use range
:
{{range .}}
<a href="/sID={{.Id}}">{{.Name}}<br></a>{{.Descr}}
{{end}}