liveBook · Manning

Block directive

As explained in Go in Practice, Second Edition

A block directive defines a template section with default content and immediately executes that section when invoked.

Use a block directive when a shared Go HTML template needs a section that a page may override. `{{block "styles" .}}…{{end}}` defines the named section with default content and executes it at that position, passing the current data (`.`). An extending template can redefine `styles` to replace the default. section 9.1.5

Required and optional sections

A base template can invoke required `title` and `content` templates with `{{template "title" .}}` and `{{template "content" .}}`; each page must define them. A `styles` block supplies default CSS, while an empty `scripts` block leaves room for page-specific scripts without requiring them. Parse the base with each extending template separately when assembling different pages. 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 template shows a default `styles` block, an empty `scripts` block, and required template invocations side by side. section 9.1.5

How Go in Practice, Second Edition covers it

How deep it goes
Explains definition, immediate execution, and overrides through a base-template example; does not examine template engine internals.
Examples
Shows default CSS in a `styles` block and an empty `scripts` block alongside required `title` and `content` sections.
What it assumes
Assumes familiarity with Go HTML templates and template data; clarifies what the block directive does.
What you can do after
Build it from scratch to share page markup while allowing optional sections to be overridden.
How it connects
Connects to template inheritance, named templates, subtemplates, and default content.

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.