How do I get nested templates like Jinja has in the python runtime. TBC what I mean is how do I have a bunch of templates inherit from a base templates, just filing in blocks of the base templates, like Jinja/django-templates does. Is it possible using just html/template
in the standard library.
If that is not a possibility, what are my alternatives. Mustache seems to be an option but would I then be missing out on those nice subtle features of html/template
like the context sensitive escaping etc.? What other alternatives are ther?
(Environment: Google App Engin, Go runtime v1, Dev - Mac OSx lion)
Thanks for reading.
Yes it is possible. A
html.Template
is actually a set of template files. If you execute a defined block in this set, it has access to all the other blocks defined in this set.If you create a map of such template sets on your own, you have basically the same flexibility that Jinja / Django offers. The only difference is that the html/template package has no direct access to the file system, so you have to parse and compose the templates on your own.
Consider the following example with two different pages ("index.html" and "other.html") that both inherit from "base.html":
And the following map of template sets:
You can now render your "index.html" page by calling
and you can render your "other.html" page by calling
With some tricks (e.g. a consistent naming convention of your template files), it's even possible to generate the
tmpl
map automatically.having worked with other template packages, now a days I mostly work with standard html/template package, I guess I was naive to not appreciate the simplicity it provides and other goodies. I use a very similar approach to accepted answer with following changes
you don't need to wrap your layouts with additional
base
template, a template block is created for every parsed file so in this case it is redundant, I also like to use the block action provided in new version of go, which allows you to have default block content in case you don't provide one in child templatesand you page templates can be the same as
now to execute the templates you need to call it like so
note, when you execute your base template, you must pass values down to the child templates, here I simply pass ".", so that everything is passed down.
template one displays {{.}}
template two displays {{.domains}} that's passed into the parent.
Note, if we used {{template "content" .}} instead of {{template "content" .}}, .domains wouldn't be accessible from the content template.
I've been coming back to this answer for days, finally bit the bullet and wrote a small abstraction layer / pre processor for this. It basically:
https://github.com/daemonl/go_sweetpl
Use Pongo, which is a super-set of Go Templates that supports the {{extends}} and {{block}} tags for template inheritance, just like Django.