Define, block and template
View as Markdowndefine and template #
define names a template. template runs one, with a pipeline as its dot:
{{define "user"}}<b>{{.name}}</b>{{end}}
{{range .users}}{{template "user" .}}{{end}}
Without a pipeline, {{template "user"}} runs it with dot set to nil.
A define prints nothing where it stands. Each named template joins the set
of the template that parsed it, so any template in the set can call it.
block #
block defines a template and runs it in place:
{{block "title" .}}Untitled{{end}}
That is short for:
{{define "title"}}Untitled{{end}}{{template "title" .}}
A later define of the same name replaces the default. Pair it with clone
to build layouts:
const layout = new Template('layout').parse(
'<title>{{block "title" .}}Untitled{{end}}</title>',
)
const about = layout.clone().parse('{{define "title"}}About{{end}}')
layout.execute() // <title>Untitled</title>
about.execute() // <title>About</title>
Sets #
Every template made from another, by define, new, parseFiles or
parseGlob, shares one set of names, functions and options. Run one by name
with executeTemplate:
const mail = new Template('mail')
mail.new('welcome').parse('Hi {{.name}}, welcome aboard.')
mail.new('reset').parse('Hi {{.name}}, here is your link: {{.link}}')
mail.executeTemplate('welcome', { name: 'Ann' })
Parsing a template that is only white space and defines leaves an existing
body alone, so you can add definitions to a template that already has one.