Optional templates in go html/template?


Given a set of templates like:


<title>Some title</title>
{{template extracss}}
<h1>Page title</h1>
{{template content .}}


{{define "content"}}
<p>page content goes here</p>


{{define "content"}}
<form>form content goes here</form>

{{define "extracss"}}<style>body{background:pink}</style>{{end}}

using this to render the template:

func Render(w http.ResponseWriter, tmpname string, data interface{}) {

    t, err := template.ParseFiles("views/layout.tpl", "views/"+tmpname+".tpl")
    // parse error
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)

    if err := t.Execute(w, data); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)

edit.tpl will render correctly as it has ‘extracss’ defined, home.tpl will not as the template parser rightly says ‘no such template “extracss”‘.

So what mechanism would I use to allow ‘optional’ templates to be used?

Any ideas?


An empty define works: {{define "extracss"}}{{end}}. It’s maybe not super elegant, but simple to understand.

Note that you don’t need to repeat the empty defines. You can put them into your master template and redefine them in the included templates only if needed.

Answered By – Thomas Kappler

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.