【问题标题】:Can template.ParseGlob() parse templates in subdirectories?template.ParseGlob() 可以解析子目录中的模板吗?
【发布时间】:2021-01-13 17:52:56
【问题描述】:

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

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

head.tplfooter.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? 我发现了this 类似的问题,但答案只是一种解决方法。

【问题讨论】:

标签: templates go


【解决方案1】:

不可以。

这里的文档很清楚:template.ParseGlob 的通配符在 filepath.Globfilepath.Glob 中的工作方式使用 filepath.Match (https://godoc.org/path/filepath#Match) 的语法,它没有 ** 进行深度匹配。

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

【讨论】:

  • pattern: { term } term: '' 匹配任何非分隔符序列 '?'匹配任何单个非分隔符 '[' [ '^' ] { character-range } ']' 字符类(必须非空) c 匹配字符 c (c != '', '?' , '\\', '[') '\\' c 匹配字符 c 字符范围:c 匹配字符 c (c != '\\', '-', ']') '\\' c 匹配字符c lo '-' hi 匹配字符 c for lo
  • 这是什么意思?
【解决方案2】:

您可以通过这种方式加载多个子目录。如果子目录不存在,我们在这里忽略。但是我们要确保可以加载第一个带有模板的目录。

func ParseTemplates() (*template.Template, error) {
    templateBuilder := template.New("")
    if t, _ := templateBuilder.ParseGlob("/*/*/*/*/*.tmpl"); t != nil {
        templateBuilder = t
    }
    if t, _ := templateBuilder.ParseGlob("/*/*/*/*.tmpl"); t != nil {
        templateBuilder = t
    }
    if t, _ := templateBuilder.ParseGlob("/*/*/*.tmpl"); t != nil {
        templateBuilder = t
    }
    if t, _ := templateBuilder.ParseGlob("/*/*.tmpl"); t != nil {
        templateBuilder = t
    }
    return templateBuilder.ParseGlob("/*.tmpl")
}

【讨论】:

    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    相关资源
    最近更新 更多