I’m new to go. But so far I’m loving it. I would like to understand the most efficient way to parse html templates.
I have a small web app with a layout template and separate nested content templates. It works just fine if I parse the templates separately in each of the handlers. e.g.
tmpl := template.Must(template.ParseFiles("templates/layout.gohtml", "templates/index.gohtml"))
tmpl.Execute(w, data)
My understanding from what I have read is that it is better to parse all the templates once globally and then execute them by name. e.g.
var templates = template.Must(template.ParseGlob("templates/*")) // global to package
...
err := templates.ExecuteTemplate(w, "index.gohtml", data) // in handler
However, it doesn’t seem to work for me. I get a blank page. I assume it’s not doing the nesting. But I’m not sure why it doesn’t work. I can’t seem to find any examples to show this scenario.
What am I missing? Should I just parse them all locally and not worry about it? What is the most efficient way to do it?
Thanks
index.gohtml:
{{define "title"}}Home{{end}}
{{define "content"}}
<p>Do something...</p>
{{end}}
layout.gohtml: (simplified)
<!doctype html>
<html lang="en">
<head>
<title>{{template "title" .}}</title>
</head>
<body>
{{template "content" .}}
</body>
</html>