告诉Golang首先执行哪个模板。

huangapple go评论85阅读模式
英文:

Telling Golang which template to execute first

问题

我有一个包含不同模板的文件夹,使用的是golang语言。主模板是main.html,还有footer.htmlheader.html。在main.html中使用以下代码加载Footer和Header:

{{template "footer.html" .}}

我使用以下代码解析文件:

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

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

然而,显示的模板总是按字母顺序排列的第一个模板,例如footer.html。如果我将main.html重命名为a.html,则模板会按照我想要的方式显示(即加载主模板并在其中执行footer和header)。

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

英文:

I have a folder with different templates in golang. The main template is main.html and there is also a footer.html and header.html. Footer and Header are loaded with

{{template "footer.html" .}} 

in main.html.

I am using this to parse the files

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

because there are other directories with different file names used aswell. So I don't want to use parseFiles.

However, the template that is displayed is always the first one in alphabetical order, e.g. footer.html. If I rename main.html to a.html the template gets displayed the way I want it to (so loading the main template and executing footer and header inside of it).

I couldn't find any documentation how to tell golang which template to use first. Is there a way to do that?

答案1

得分: 1

了解到template.Template可能是(通常是)多个模板的集合。模板包含与模板关联的模板映射。当使用template.ParseFiles()template.ParseGlob()时,返回的template.Template将指定从多个文件中解析的第一个模板。您可以在这里阅读更多信息:https://stackoverflow.com/questions/41176355/go-template-name/41187671#41187671

不要使用Template.Execute()(根据上述内容,将执行第一个解析的模板),而是使用Template.ExecuteTemplate()方法,您可以指定要执行的模板,通过模板的名称指定:

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

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

英文:

Know that a template.Template may be (usually is) a collection of multiple templates. The template contains a map of the associated templates. When using template.ParseFiles() or template.ParseGlob(), the returned template.Template will designate the first template that was parsed (from the multiple files). You can read more about this here: https://stackoverflow.com/questions/41176355/go-template-name/41187671#41187671

Instead of using Template.Execute() (which –based on the above– will execute the first parsed template) use the Template.ExecuteTemplate() method where you can specify which template you want to execute, specified by its name:

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

This will execute the template named "main.html" no matter in what order the template files were parsed (or later added to the template collection).

huangapple
  • 本文由 发表于 2017年3月5日 14:46:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/42605373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定