title: Go - html/template, template.ParseGlob() and code re-use
body: <p>I'm trying to get my head around embedding templates using <code>html/template</code> in Go. I very much like the logic-less template design and I have confidence in its ability to safely escape things as expected (sometimes other template libs get this wrong).</p>
  
  <p>I am, however, having a bit of a problem trying to implement a little helper to render my templates in my HTTP handlers based on the "final" template name. My base.tmpl is effectively "standard" across all of my pages, and in cases where it isn't I can set <code>{{ template checkoutJS }}</code> in base.tmpl and add some per-page JS by setting <code>{{ define checkoutJS }}https://path.to/extra.js {{ end }}</code>.</p>
  
  <p>I want to be able to say <code>renderTemplate(w, "template_name.tmpl", data)</code> in my HTTP handlers, where <code>data</code> is a map[string]interface{} containing strings or structs with whatever I wish to fill in.</p>
  
  <p>Here's the code so far:</p>
  
  <p><strong>base.tmpl</strong></p>
  
  <pre><code>{{ define "base" }}
  &lt;!DOCTYPE html&gt;
  &lt;html lang="en"&gt;
  &lt;head&gt;
  &lt;title&gt;{{ template "title" . }}&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;div id="sidebar"&gt;
  ...
  &lt;/div&gt;
  
  {{ template "content" }}
  
  &lt;div id="footer"&gt;
  ...
  &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>create_listing.tmpl</strong></p>
  
  <pre><code>{{ define "title" }}Create a New Listing{{ end }}
  
  {{ define "content" }}
  
  &lt;form&gt;
    ...
  &lt;/form&gt;
  
  {{ end }}
  </code></pre>
  
  <p><strong>login_form.tmpl</strong></p>
  
  <pre><code>{{ define "title" }}Login{{ end }}
  
  {{ define "content" }}
  
  &lt;form&gt;
    ...
  &lt;/form&gt;
  
  {{ end }}
  </code></pre>
  
  <p><strong>main.go</strong></p>
  
  <pre><code>package main
  
  import (
    "fmt"
      "github.com/gorilla/mux"
      "html/template"
      "log"
      "net/http"
  )
  
  // Template handling shortcuts
  var t = template.New("base")
  
  func renderTemplate(w http.ResponseWriter, tmpl string, data map[string]interface{}) {
  
      err := t.ExecuteTemplate(w, tmpl, data)
  
    // Things will be more elegant than this: just a placeholder for now!
      if err != nil {
          http.Error(w, "error 500:"+" "+err.Error(), http.StatusInternalServerError)
      }
  }
  
  func monitorLoginForm(w http.ResponseWriter, r *http.Request) {
  
      // Capture forms, etc.
  
      renderTemplate(w, "login_form.tmpl", nil)
  }
  
  func createListingForm(w http.ResponseWriter, r *http.Request) {
  
      // Grab session, re-populate form if need be, generate CSRF token, etc
  
      renderTemplate(w, "create_listing.tmpl", nil)
  }
  
  func main() {
  
      r := mux.NewRouter()
  
      r.HandleFunc("/monitor/login", monitorLoginForm)
  
      http.Handle("/", r)
      log.Fatal(http.ListenAndServe(":8000", nil))
  
  }
  
  func init() {
  
      fmt.Println("Starting up.")
      _, err := t.ParseGlob("templates/*.tmpl")
      if err != nil {
          log.Fatal("Error loading templates:" + err.Error())
      }
  }
  </code></pre>
  
  <p>This compiles, but I get back an empty response from my handler. Note that I don't have a route for the second handler: that code is there just to show how I want to call <code>renderTemplate()</code> from handlers.</p>