Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moraes/3076791 to your computer and use it in GitHub Desktop.
Save moraes/3076791 to your computer and use it in GitHub Desktop.
An idea for {{block}} semantics in Go's text/template

{{block}} in text/template

We can achieve what is known as "template inheritance" in other template engines using the {{block}} tag. A {{block}} is a replaceable fragment inside a template. Here's an example:

{{define "Base"}}

<p>A header</p>

{{block body}}

<p>A body</p>

{{end}}}

<p>A footer</p>

{{end}}}

The "body" block is rendered normally when this template is called directly. But when it is called by another template, the blocks defined in the other template receive higher priority and can override the ones from the original template. Here is a template that "extends" the previous template, overriding the "body" block:

{{define "Page"}}

{{block body}}

<p>Another body</p>

{{end}}

{{template "Base" .}}

{{end}}

When the "Page" template is executed, it calls the "Base" template and its own "body" block overrides the original one.

This is even better than inheritance because you are not restricted to a single parent template: you can compose multiple calls to other templates, possibly overriding blocks from any of them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment