liveBook · Manning

Base template

As explained in Go in Practice, Second Edition

A base template is a template containing shared markup and references to sections supplied or overridden by extending templates.

When pages share the same HTML structure, put that markup in a base template. Define named sections for page-specific content instead of duplicating the surrounding document. section 9.1.5

Separate required content from optional overrides:

  • Reference named title and content templates where each page must supply markup. section 9.1.5
  • Use blocks for styles and scripts when a page may replace defaults or leave them empty. section 9.1.5
Listing 9.11 A base template to inherit from
{{define "base"}}<!DOCTYPE HTML>   #1
<html>
  <head>
    <meta charset="utf-8">
    <title>{{template "title" .}}</title>    #2
    {{ block "styles" . }}<style>   #3
      h1 {                          #3
        color: #400080              #3
      }                             #3
    </style>{{ end }}               #3
  </head> #3
  <body>
     <h1>{{template "title" .}}</h1>
     {{template "content" .}}
     {{block "scripts" .}}{{end}}    #4
  </body>
</html>{{end}}   #5

The base layout shows where title, content, styles, and scripts enter the shared HTML. section 9.1.5

With Go’s html/template, parse the base alongside each page template as a separate template set. This lets pages define the same section names without sharing one another’s definitions. section 9.1.5

How Go in Practice, Second Edition covers it

How deep it goes
Shows required template definitions, optional blocks, and Go setup for separate page template sets.
Examples
Uses a shared HTML layout, a user page, and a page overriding styles.
What you can do after
Build it from scratch using html/template definitions and blocks for reusable page layouts.
How it connects
Connects template inheritance with named templates, blocks, and html/template.

Also explained in

Compare how 2 books explain base template →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.