Template composition
As templates grow, they may become repetitive. To reduce such repetition, the Go template system offers named blocks (components) that can be reused within a template, just like functions in a program. Then, the final template can be composed of these components.
How to do it...
You can create template “components” that you can reuse in multiple contexts. To define a named template, use the {{define "name"}} construct:
{{define "template1"}}
...
{{end}}
{{define "template2"}}
...
{{end}} Then, call that template using the {{template "name" .}} construct as if it is a function with a single argument:
{{template "template1" .}}
{{range .List}}
{{template "template2" .}}
{{end}} How it works...
The following example prints a book list using a named template:
package main import ( "os" ...