Telling Golang which template to execute first

自闭症网瘾萝莉.ら 提交于 2019-12-11 05:22:18

问题


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:


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: Go template name

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).



来源:https://stackoverflow.com/questions/42605373/telling-golang-which-template-to-execute-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!