猿问

template.ParseGlob() 可以解析子目录中的模板吗?

为了清理模板文件夹,我想将常用模板保存在子文件夹中。目前我有以下文件结构:


main.go

templates/index.tpl            # Main template for the main page

templates/includes/head.tpl

templates/includes/footer.tpl

head.tpl并且footer.tpl将在被调用index.tpl,它看起来像这样:


{{ template "head" . }}

    <h1>My content</h1>

{{ template "footer" .}}

此外,文件使用template.ParseGlob(). 这是摘录自main.go:


var views = template.Must(template.ParseGlob("src/templates/**/*"))


func Render(rw http.ResponseWriter, temp string, data interface{}) {

    err := views.ExecuteTemplate(rw, temp, data)


    if err != nil {

        http.Error(rw, err.Error(), http.StatusInternalServerError)

    }

}


func Index(rw http.ResponseWriter, req *http.Request) {

    Render(rw, "index.tpl", nil)

}

每次打开浏览器时,都会收到以下错误消息:html/template: "index.tpl" is undefined.


是否有可能index.tpl被这种 glob 模式忽略?我发现了这个类似的问题,但答案只是一个解决方法。


牛魔王的故事
浏览 192回答 2
2回答
随时随地看视频慕课网APP

相关分类

Go
我要回答