First, you should check errors returned by the Template.ParseFiles()
method. You store the returned error, but you only check it at the end (and by then it is overwritten like 3 times).
Next, never parse templates in the request handler, it's too time consuming and resource wasting. Do it once at startup (or on first demand). For details see It takes too much time when using "template" package to generate a dynamic web page to client in golang.
Next, you can parse multiple files at once, just enumerate all when passing to the Template.ParseFiles()
function (there is a method and a function).
Know that Template.Execute()
only executes a single (named) template. You have 3 associated templates, but only the "base.html"
template is executed by your code. To execute a specific, named template, use Template.ExecuteTemplate()
. For details, see Telling Golang which template to execute first.
First you should define a structure of your templates, decide which templates include others, and execute the "wrapper" template (using Template.ExecuteTemplate()
). When you execute a template that invokes / includes another template, you have the possibility to tell what value (data) you what to pass to its execution. When you write {{template "something" .}}
, that means you want to pass the value currently pointed by dot to the execution of the template named "something"
. Read more about this: golang template engine pipelines.
To learn more about template association and internals, read this answer: Go template name.
So in your case I would imagine that "base.html"
is the wrapper, outer template, which includes "menu.html"
and "users.html"
. So "base.html"
should contain lines similar to this:
{{template "menu.html" .}}
{{template "users.html" .}}
The above lines will invoke and include the results of the mentioned templates, passing the data to their execution that was passed to "base.html"
(if dot was not changed).
Parse the files using the template.ParseFiles()
function (not method) like this:
var t *template.Template
func init() {
var err error
t, err = template.ParseFiles(
"public/base.html", "public/menu.html", "public/users.html")
if err != nil {
panic(err) // handle error
}
}
And execute it like this in your handler:
err := t.ExecuteTemplate(w, "base.html", context)