问题
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