What you should know is that a value of template.Template
can be a collection of multiple templates, see its Template.Templates()
method which returns this collection.
Each template in the collection has a unique name that it can be referred to by (see Template.Name()
). And there is a {{template "name" pipeline}}
action, and using that you can include other templates in a template, another template which is part of the collection.
See this example. Let's define 2 templates:
const tmain = `<html><body>
Some body. Now include the other template:
{{template "content" .}}
</body></html>
`
const tcontent = `I'M THE CONTENT, param passed is: {{.Param}}`
As you can see, tmain
includes another template named "content"
. You can use the Template.New()
method (stressing: method, not to be confused with the func template.New()
) to create a new associated, named template that will be part of the template whose method you're calling. As a result, they can refer to each other, e.g. they can include each other.
Let's see code that parses these 2 templates into one template.Template
so they can refer to each other (error check omitted for brevity):
t := template.Must(template.New("main").Parse(tmain))
t.New("content").Parse(tcontent)
param := struct{ Param string }{"paramvalue"}
if err := t.ExecuteTemplate(os.Stdout, "main", param); err != nil {
fmt.Println(err)
}
Output (try it on the Go Playground):
<html><body>
Some body. Now include the other template:
I'M THE CONTENT, param passed is: paramvalue
</body></html>
Alternative
Also note that if you have many and bigger templates, this becomes less readable and maintainable. You should consider saving your templates as files, and you can use template.ParseFiles()
and template.ParseGlob()
, both which can parse multiple files at once and they build the template collection from them, so they can refer to each other. The names of the templates will be the names of the files.