Golang:解析目录和子目录中的所有模板吗? [英] Golang: Parse all templates in directory and subdirectories?
本文介绍了Golang:解析目录和子目录中的所有模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的目录结构:
app/
template/
layout/
base.tmpl
index.tmpl
template.ParseGlob("*/*.tmpl")
解析 index.tmpl
,但不解析 base.tmpl
中的布局
子目录.有没有一种方法可以递归地解析所有模板?
template.ParseGlob("*/*.tmpl")
parses index.tmpl
but not base.tmpl
in the layout
subdirectory. Is there a way to parse all templates recursively?
推荐答案
并非没有实现自己的功能,我一直在使用类似的东西
Not without implementing your own function to do it, I've been using something like this
func ParseTemplates() *template.Template {
templ := template.New("")
err := filepath.Walk("./views", func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, ".html") {
_, err = templ.ParseFiles(path)
if err != nil {
log.Println(err)
}
}
return err
})
if err != nil {
panic(err)
}
return templ
}
这将解析您的所有模板,然后您可以通过调用它们的名称来渲染它们,例如
This will parse all your templates then you can render them by calling their names e.g.
template.ExecuteTemplate(w,"home",nil)
这篇关于Golang:解析目录和子目录中的所有模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文