【问题标题】:Telling Golang which template to execute first告诉 Golang 先执行哪个模板
【发布时间】:2017-03-05 06:46:36
【问题描述】:

我在 golang 中有一个包含不同模板的文件夹。主模板是main.html,还有一个footer.htmlheader.html。页脚和页眉加载了

{{template "footer.html" .}} 

main.html中。

我正在使用它来解析文件

templates, _ := template.ParseGlob("Templates/" + template_name + "/*.html")

因为还有其他目录使用不同的文件名。所以我不想使用 parseFiles

但是,显示的模板始终是按字母顺序排列的第一个模板,例如footer.html。如果我将 main.html 重命名为 a.html,则模板将以我想要的方式显示(因此加载主模板并在其中执行页脚和页眉)。

我找不到任何文档如何告诉 golang 首先使用哪个模板。有没有办法做到这一点?

【问题讨论】:

    标签: templates go go-templates


    【解决方案1】:

    知道template.Template 可能(通常是)多个模板的集合。该模板包含相关模板的映射。当使用template.ParseFiles()template.ParseGlob() 时,返回的template.Template 将指定被解析的第一个模板(来自多个文件)。你可以在这里阅读更多信息:Go template name

    使用Template.ExecuteTemplate() 方法代替使用Template.Execute()(基于上述方法将执行第一个解析的模板),您可以在其中指定要执行的模板,由其名称指定:

    err := templates.ExecuteTemplate(w, "main.html", data)
    

    这将执行名为 "main.html" 的模板,无论模板文件以何种顺序被解析(或稍后添加到模板集合中)。

    【讨论】:

      猜你喜欢
      • 2011-06-20
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      相关资源
      最近更新 更多