HTML Templates

Serving HTML is an important job for some web applications. Go has one of my
favorite templating languages to date. Not for its features, but for its
simplicity and out of the box security. Rendering HTML templates is almost as
easy as rendering JSON using the ‘html/template’ package from the standard
library. Here is what the source code for rendering HTML templates looks like:

  1. package main
  2. import (
  3. "html/template"
  4. "net/http"
  5. "path"
  6. )
  7. type Book struct {
  8. Title string
  9. Author string
  10. }
  11. func main() {
  12. http.HandleFunc("/", ShowBooks)
  13. http.ListenAndServe(":8080", nil)
  14. }
  15. func ShowBooks(w http.ResponseWriter, r *http.Request) {
  16. book := Book{"Building Web Apps with Go", "Jeremy Saenz"}
  17. fp := path.Join("templates", "index.html")
  18. tmpl, err := template.ParseFiles(fp)
  19. if err != nil {
  20. http.Error(w, err.Error(), http.StatusInternalServerError)
  21. return
  22. }
  23. if err := tmpl.Execute(w, book); err != nil {
  24. http.Error(w, err.Error(), http.StatusInternalServerError)
  25. }
  26. }

This is the following template we will be using. It should be placed in a
templates/index.html file in the directory your program is run from:

  1. <html>
  2. <h1>{{ .Title }}</h1>
  3. <h3>by {{ .Author }}</h3>
  4. </html>

Exercises

  1. Look through the docs for text/template and html/template package. Play with the templating language a bit to get a feel for its goals, strengths, and weaknesses.
  2. In the example we parse the files on every request, which can be a lot of performance overhead. Experiment with parsing the files at the beginning of your program and executing them in your http.Handler (hint: make use of the Copy() method on html.Template).
  3. Experiment with parsing and using multiple templates.