在我的html模板中:
{{range $index, $results := .}}
{{add $index 1}}{{.Title}}{{.Description}}{{end}}
在执行代码中,我编写了一个传递给FuncMap的函数:
func add(x, y int) int {
return x + y
}
在我的处理程序中:
type ToDo struct {
Id int
Title string
Description string
}
func IndexHandler(writer http.ResponseWriter, request *http.Request) {
results := []ToDo{ToDo{5323, "foo", "bar"}, ToDo{632, "foo", "bar"}}
funcs := template.FuncMap{"add": add}
temp := template.Must(template.New("index.html").Funcs(funcs).ParseFiles(templateDir + "/index.html"))
temp.Execute(writer, results)
}