小编典典

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

go

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

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模式所忽略?我发现类似的问题,但答案仅能解决。


阅读 583

收藏
2020-07-02

共1个答案

小编典典

不,它不能。

这里的文档非常清楚:template.ParseGlob像in中那样进行globbing
filepath.Globfilepath.Glob使用filepath.Matchhttps://godoc.org/path/filepath#Match)的语法,该语法没有**深度匹配。

(认真阅读文档 确实有 帮助。)

2020-07-02