问题描述

 templates/template_name.html 
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 
templates/edit.htmlview.htmlgo run wiki.go
html/template: "templates/view.html" is undefined

有什么可能的想法吗?

推荐答案

 ParseFiles  ExecuteTemplate 
ParseFilesExecuteTemplate
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)
    }
}

这篇关于Golang,模板未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!