Yes it is possible. A html.Template is actually a collection of template files. If you execute a specific block in this set, it has access to all other blocks defined in this set.
If you create a map of such template sets on your own, you have the same flexibility that Jinja / Django offers. The only difference is that the html / template package does not have direct access to the file system, so you will have to analyze and compile the templates yourself.
Consider the following example with two different pages ("index.html" and "other.html") that inherit from "base.html":
// Content of base.html: {{define "base"}}<html> <head>{{template "head" .}}</head> <body>{{template "body" .}}</body> </html>{{end}} // Content of index.html: {{define "head"}}<title>index</title>{{end}} {{define "body"}}index{{end}} // Content of other.html: {{define "head"}}<title>other</title>{{end}} {{define "body"}}other{{end}}
And the following template sets map:
tmpl := make(map[string]*template.Template) tmpl["index.html"] = template.Must(template.ParseFiles("index.html", "base.html")) tmpl["other.html"] = template.Must(template.ParseFiles("other.html", "base.html"))
Now you can display the "index.html" page by calling
tmpl["index.html"].Execute("base", data)
and you can display the page "other.html" by calling
tmpl["other.html"].Execute("base", data)
With some tricks (for example, a consistent naming convention for your template files), it is even possible to create a tmpl map automatically.
tux21b Jul 13 2018-12-12T00: 00Z
source share