template.ParseGlob()可以在子目录中解析模板吗? [英] Can template.ParseGlob() parse templates in subdirectories?
问题描述
要清理模板文件夹,我想将常用模板保存在子文件夹中。目前,我有以下文件结构:
main.go
templates / index.tpl#主页面
templates / includes / head.tpl
templates / includes / footer.tpl
此外,文件使用 每次打开我的浏览器时,都会收到以下错误消息: 是否有可能, 这里的文档非常清晰: (It 真的有助于阅读文档仔细。) To clean up the template folder I would like to save common templates inside a subfolder. Currently I've the following file structure: Furthermore the files are parsed using Everytime I open my browser I get this error message: Is it possible, that No it cannot. The documentation is pretty clear here: Globbing for (It really helps to read the documentation carefully.) 这篇关于template.ParseGlob()可以在子目录中解析模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
在 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 $ c的语法$ c>( https://godoc.org/path/filepath#Match ),它没有
**
用于深度匹配。
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" .}}
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)
}
html/template: "index.tpl" is undefined
.index.tpl
is ignored with this glob pattern?
I found this similar question, but the answers present only a work around.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.