登录
首页 >  Golang >  Go问答

Golang,模板未定义

来源:stackoverflow

时间:2024-03-16 18:09:26 284浏览 收藏

在 Golang 中使用模板时,将模板文件移动到单独的文件夹后,可能会遇到“模板未定义”错误。此错误表明模板引擎无法找到指定的模板文件。要解决此问题,需要确保模板引擎知道模板文件的正确路径。

问题内容

我目前正在尝试使用 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.htmlview.html 文件。我运行完整的代码: go run wiki.go 但是当我尝试访问网页时出现以下错误:

html/template: "templates/view.html" is undefined

知道会发生什么吗?


解决方案


就像@volker所说,我们在parsefiles中使用模板的路径,在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,模板未定义》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>