做的时候ExecuteTemplate 我看到所有使用 &whateversruct{Title: "title info", Body: "body info"} 的示例将数据发送到模板以替换信息。我想知道是否有可能不必在我的处理程序函数之外创建一个结构体,因为我拥有的每个处理程序函数都不会具有相同的标题、正文。能够向它发送替换模板信息的 map 会很好。有什么想法或想法吗?
目前 - 松散地写
type Info struct {
Title string
Body string
}
func View(w http.ResponseWriter) {
temp.ExecuteTemplate(w, temp.Name(), &Info{Title: "title", Body: "body"})
}
似乎没有必要创建结构。并且您创建的每个函数的结构都不相同。所以你必须为每个函数创建一个结构(我知道)。
Best Answer-推荐答案
为了增加凯文的回答:匿名结构将产生几乎相同的行为:
func View(w http.ResponseWriter) {
data := struct {
Title string
Body string
} {
"About page",
"Body info",
}
temp.ExecuteTemplate(w, temp.Name(), &data)
}
关于go - 全局模板数据,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/12484398/
|