liveBook · Manning

Nested template

As explained in Go in Practice, Second Edition

A nested template is a template that includes or invokes another template as part of rendering output.

When several pages share HTML, keep the repeated markup in a subtemplate rather than copying it into every page. A parent template includes that subtemplate when it renders. section 9.1.5

Listing 9.8 Index template including head template
<!DOCTYPE HTML>
<html>
  {{template "head.html" .}}     #1
  <body>
       <h1>{{.Title}}</h1>
       <p>{{.Content}}</p>
  </body>
</html>

The index template replaces its head markup with {{template "head.html" .}}. The final dot passes the parent’s data to the included template. section 9.1.5

Render a page with a shared head

Put the head markup in head.html, where {{.Title}} can use the page’s title. Parse both files with template.ParseFiles("index.html", "head.html"), then render with ExecuteTemplate(w, "index.html", page). section 9.1.5

How Go in Practice, Second Edition covers it

How deep it goes
Explains the inclusion directive, passed data, file parsing, and rendering in a Go HTTP handler.
Examples
Uses an index template that includes a head template and passes page data from an HTTP handler.
What you can do after
Apply it via Go’s html/template to render pages with shared markup.
How it connects
Connects nested templates to HTML rendering, template inheritance, and template data.

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.