template.ParseGlob()可以在子目录中解析模板吗? [英] Can template.ParseGlob() parse templates in subdirectories?

查看:668
本文介绍了template.ParseGlob()可以在子目录中解析模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  main.go 
templates / index.tpl#主页面
templates / includes / head.tpl
templates / includes / footer.tpl



index.tpl中调用

head.tpl footer.tpl / code>,看起来像这样:

  {{templatehead。 }} 
< h1>我的内容< / h1>
{{templatefooter。}}

此外,文件使用 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索引(rw http.ResponseWriter,req * http.Request){
Render(rw​​,index.tpl,nil)
}

每次打开我的浏览器时,都会收到以下错误消息: html / template:index .tpl是未定义的



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

解决方案

这里的文档非常清晰: template.ParseGlob 的全局工作方式类似于 filepath.Glob filepath.Glob 使用 filepath.Match https://godoc.org/path/filepath#Match ),它没有 ** 用于深度匹配。



(It 真的有助于阅读文档仔细。)


To clean up the template folder I would like to save common templates inside a subfolder. Currently I've the following file structure:

main.go
templates/index.tpl            # Main template for the main page
templates/includes/head.tpl
templates/includes/footer.tpl

head.tpl and footer.tpl will be called within index.tpl, which looks like this:

{{ template "head" . }}
    <h1>My content</h1>
{{ template "footer" .}}

Furthermore the files are parsed using template.ParseGlob(). Here's an excerpt from 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)
}

Everytime I open my browser I get this error message: html/template: "index.tpl" is undefined.

Is it possible, that index.tpl is ignored with this glob pattern? I found this similar question, but the answers present only a work around.

解决方案

No it cannot.

The documentation is pretty clear here: Globbing for template.ParseGlob works like in filepath.Glob and filepath.Glob uses the syntax of filepath.Match (https://godoc.org/path/filepath#Match) which has no ** for a deep match.

(It really helps to read the documentation carefully.)

这篇关于template.ParseGlob()可以在子目录中解析模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆