Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moraes/3069983 to your computer and use it in GitHub Desktop.
Save moraes/3069983 to your computer and use it in GitHub Desktop.
My crazy idea to overdo the convenience of template inheritance using composition

My crazy idea to overdo the convenience of template inheritance using composition

This idea will be patented soon. Go away, Apple.

TL;DR: Django created template inheritance and people thought it was awesome and everybody copied it. Go doesn't have it, people cried. We got an idea to make people happy again, without changing text/template syntax.

Here we Go

Go supports templates defined inside templates using the {{define}} tag. Good. The idea is to make templates defined this way to become a variable in the template where they are defined. For example:

{{define "message"}}

Hello, world!

{{end}}

When this template is parsed, the "message" template is added to the the local variables table, accessible as .message. The name must start with lower case, so there's no collision with the data passed during execution.

That's all we needed: now we can pass a template around. Imagine that we have a template named "Base" that looks like this:

<p>A header</p>

{{template .body}}

<p>A footer</p>

That's out "master" template, the one that would be "extended" if this was Django or Jinja2 (it is not).

(text/template doesn't support calling a template with variable name, like above. this must change)

Now, and please note: without inheritance, we can compose a template that fills the .body part of the base template:

{{define "body"}}

<p>A body</p>

{{end}}

{{template "Base" .}}

Look, no hands! "Base" is executed passing the dot, which includes the .body variable, which is our body template filler. No inheritance, no complication.

Please tell me if it is not crazy.

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