liveBook · Manning

ExecuteTemplate

As explained in Go in Practice, Second Edition

ExecuteTemplate is a Go template execution method that renders a named template with supplied data.

Use `ExecuteTemplate` when several named templates have been parsed together and you need to choose which one renders. Unlike `Execute`, which uses the first template listed in `ParseFiles`, it takes the template name explicitly. section 9.1.5

Render a page with a shared head

Parse `index.html` and `head.html` into one template object, then call `t.ExecuteTemplate(w, "index.html", p)` in an HTTP handler. The index template can include `{{template "head.html" .}}`; passing `.` makes the page data, including `Title`, available to the head template. section 9.1.5

Listing 9.10 Using the nested templates
package main

import (
     "html/template"
     "net/http"
)

var t *template.Template
func init() {
     t = template.Must(template.ParseFiles("index.html
     ", "head.html"))                                    #1
}

type Page struct {
     Title, Content string
}

func displayPage(w http.ResponseWriter, r *http.Request) {
     p := &Page{
            Title:   "An Example",
            Content: "Have fun stormin' da castle.",
     }
     t.ExecuteTemplate(w, "index.html", p)   #2
}

func main() {
     http.HandleFunc("/", displayPage)   #3
     http.ListenAndServe(":8080", nil)   #3
}

The complete Go handler parses both files and selects `index.html` for the HTTP response. section 9.1.5

How Go in Practice, Second Edition covers it

How deep it goes
Shows parsing, named execution, and data passed to a nested template; does not examine execution internals.
Examples
Uses an index page that includes a head template and an HTTP handler that renders the index by name.
What it assumes
Assumes basic Go structs and HTTP handlers while demonstrating how to parse and select templates.
What you can do after
Apply it via Go’s `html/template` package to render a chosen template from a parsed set.
How it connects
Connects `ParseFiles`, `Execute`, nested templates, and HTTP handlers.

Also explained in

Compare how 2 books explain ExecuteTemplate →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.