Prevent overwriting of blocks with same name in Go html/template

Viewed 35

I'm having difficulty in rendering the correct content using templates in Go.

I have a base template (base.tmpl) and 2 child templates (a.tmpl and b.tmpl).

// base.tmpl
{{ define "base" }}
  {{ template "header" . }}
  {{ template "content" . }}
  {{ template "footer" . }}
{{ end }}
// a.tmpl
{{ template "base" . }}
{{ block "content" . }}
  This is a.tmpl
{{ end }}
// b.tmpl
{{ template "base" . }}
{{ block "content" . }}
  This is b.tmpl
{{ end }}

When executing a.tmpl the contents of the content block in b.tmpl are inserted and also duplicated.

For example, rendering a.tmpl results in a page displaying:

This is b.tmpl
This is b.tmpl

I am assuming this is because when parsing the templates, Go keeps b.tmpl's content block definition as the most recent.

I'm wondering if there's a way where I can have a base template and define the main content of pages, or perhaps if I'm approaching the templates incorrectly.

1 Answers

Parse the templates for a and b separately.

atmpl, err := template.ParseFiles("base.tmpl", "a.tmpl")
if err != nil { /* handle error */ }

btmpl, err := template.ParseFiles("base.tmpl", "b.tmpl")
if err != nil { /* handle error */ }
Related