Golang,模板未定义 [英] Golang, template is undefined
问题描述
我目前正在尝试使用golang创建一个小型Web应用程序,并且正在遵循其网页上的教程( https://golang.org/doc/articles/wiki/final.go ).与其将模板与其余代码放在同一文件夹中,我不打算将它们移至 templates/template_name.html
.
I'm currently trying to create a small web application using golang and I'm following the tutorial on their webpage (https://golang.org/doc/articles/wiki/final.go). Instead of having the templates on the same folder as the rest of the code I'm trying to move them into templates/template_name.html
.
对于模板渲染,我使用以下代码:
For template rendering I'm using the following code:
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)
}
}
例如,我的View处理程序如下:
And for example my View handler is the following:
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
,但是当我尝试访问网页时,出现以下错误:
I have the templates/
folder with the edit.html
and view.html
file inside. I run the full code with: go run wiki.go
but when I try to access the webpage I get the following error:
html/template: "templates/view.html" is undefined
有什么可能的想法吗?
推荐答案
就像@Volker所说,我们在 ParseFiles
中使用模板的路径,在 ExecuteTemplate
中使用文件名:
Like @Volker said, we use the template's path in ParseFiles
and the filename in ExecuteTemplate
:
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, tmpl+".html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
我的实现: https://github.com/librity/gowiki
这篇关于Golang,模板未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!