I'm looking to use template blocks in Golang to get a "template inheritance" style overwrite logic.
I have a base.html
template which is something like this:
<title>{{block "title" .}}Default Title{{end}}</title>
<body>{{block "content" .}}This is the default body.{{end}}</body>
And then I have a template blogpost.html
like so:
{{define "title"}}Blog Post Title{{end}}
{{define "content"}}Lorem Ipsum...{{end}}
All of this works flawlessly as long as I just use ParseFiles
and then execute the template
t, err := template.ParseFiles("./templates/base.html", "./templates/blogpost.html")
t.Execute(t, viewModel)
The way I did it was calling ParseFiles
once for every template I needed to render. E. g. I did not call templates by name.
However, I now want to also use Template Functions. Now I need to call template.New
to get an empty template, assign a name, add the template functions and parse the files (Funcs
"must be called before the template is parsed") :
tpl := template.Must(
template.New("somename").Funcs(sprig.FuncMap()).ParseGlob("*.html")
)
This seems to be incompatible with my idea of template inheritance. I have to ExecTemplate
with my base.html
as a parameter in order to get any output. However, I'd like to load one base template and many content templates. Then call the content templates by name.
Am I misunderstanding the way that Golang templates and/or Blocks are intended to be used? What's an elegant and idiomatic way to perform this kind of task?