I'm looking to see if there is a better (faster, more organised) way to split up my templates in Go. I strongly prefer to stick to html/template (or a wrapper thereof) since I trust its security model.
- Right now I use
template.ParseGlob
to parse all of my template files in withininit()
. - I apply template.Funcs to the resulting templates
- I set a
$title
in each template (i.e.listing_payment.tmpl
) and pass this to the content template. - I understand that
html/template
caches templates in memory once parsed - My handlers only call
t.ExecuteTemplate(w, "name.tmpl", map[string]interface{})
and don't do any silly parsing on each request. -
I compose templates from multiple pieces (and this is the bit I find clunky) as below:
{{ $title := "Page Title" }} {{ template "head" $title }} {{ template "checkout" }} {{ template "top" }} {{ template "sidebar_details" . }} {{ template "sidebar_payments" }} {{ template "sidebar_bottom" }} <div class="bordered-content"> ... {{ template "listing_content" . }} ... </div> {{ template "footer"}} {{ template "bottom" }}
My three questions are:
Is this performant, or do the multiple
{{ template "name" }}
tags result in a potential per-request performance hit? I see a lot ofwrite - broken pipe
errors when stress testing heavier pages. This might just be due to socket timeouts (i.e. socket closing before the writer can finish) rather than some kind of per-request composition, though (correct me if otherwise!)Is there a better way to do this within the constraints of the html/template package? The first example in Django's template docs approaches what I'd like. Extend a base layout and replace the title, sidebar and content blocks as needed.
Somewhat tangential: when template.ExecuteTemplate returns an error during a request, is there an idiomatic way to handle it? If I pass the writer to an error handler I end up with soup on the page (because it just continues writing), but a re-direct doesn't seem like idiomatic HTTP.