【发布时间】:2018-09-25 14:20:02
【问题描述】:
我目前正在尝试使用 golang 创建一个小型 Web 应用程序,并且我正在关注他们网页上的教程 (https://golang.org/doc/articles/wiki/final.go)。我没有将模板与其余代码放在同一文件夹中,而是尝试将它们移动到templates/template_name.html。
对于模板渲染,我使用以下代码:
var templates = template.Must(template.ParseFiles("templates/edit.html", "templates/view.html"))
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
err := templates.ExecuteTemplate(w, "templates/"+tmpl+".html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
例如,我的视图处理程序如下:
func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
p, err := loadPage(title)
if err != nil {
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
return
}
renderTemplate(w, "view", p)
}
我有 templates/ 文件夹,里面有 edit.html 和 view.html 文件。我使用以下代码运行完整代码:go run wiki.go,但是当我尝试访问该网页时,出现以下错误:
html/template: "templates/view.html" is undefined
知道会发生什么吗?
【问题讨论】:
-
阅读 ParseFiles 的文档。模板的名称不是文件路径。所以修复
"templates/"+tmpl+".html" -
我已经阅读了文档,但我不明白它是如何在没有指示的情况下到达文件夹内的模板的。我有点迷路了。
-
正如@Volker 所写,模板名称只是
"view.html",而不是"templates/view.html"。请参阅相关/可能的重复:Go template name. -
你试过简单的“edit.html”吗?
-
确保保存代码,运行
go clean,重新构建代码并运行它。
标签: go