[Templates] (Re)define a block from a base template?

I’m exploring the capabilities of Caddy’s template system and have built a simple base template in the index.html file. My goal is to use this template as the base for all other pages by only overriding a few selected blocks from the base. This does not work as I expected, however.

This is a simplified example of my code:


{{ block "baseTemplate" . }}
   {{ block "head" . }}<head>...head code goes here</head>{{ end }}
     {{ block "header" . }}<header>...head code goes here</header>{{ end }}
     {{ block "main" . }}<main>...most of the page content goes here</main>{{ end }}
{{ end }}

This works great! Everything is rendered as expected when hitting my index.html. Fetching my “baseTemplate” into another page also works without problems by doing this:


{{ import "/index.html" }}
{{ template "baseTemplate" }}

Trying to override the main block however, does not work. The content from “main” is the same as the original content in the index.html:

{{ import "/index.html" }}
{{ define "main" }}<main>...new content goes here</main>{{ end }}
{{ template "baseTemplate" }}

Why does this not work? It sure would be really handy to construct a base template like this to keep things DRY :smirk:

EDIT: To make sure the problem wasn’t that I have nested the blocks, I tried defining the baseTemplate instead of the main, but with the same result.

EDIT2: Go’s documentation leaves me with the impression that what I have done should be possible:

{{block "name" pipeline}} T1 {{end}}
A block is shorthand for defining a template
	{{define "name"}} T1 {{end}}
and then executing it in place
	{{template "name" pipeline}}

The typical use is to define a set of root templates that are
then customized by redefining the block templates within.
1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.