Multiple files using template.ParseFiles in golang

Tech163 picture Tech163 · Sep 1, 2012 · Viewed 12.7k times · Source

For example.go, I have

package main

import "html/template"
import "net/http"

func handler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("header.html", "footer.html")
    t.Execute(w, map[string] string {"Title": "My title", "Body": "Hi this is my body"})
}

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

In header.html:

Title is {{.Title}}

In footer.html:

Body is {{.Body}}

When going to http://localhost:8080/, I only see "Title is My title", and not the second file, footer.html. How can I load multiple files with template.ParseFiles? What's the most efficient way to do this?

Thanks in advance.

Answer

user634175 picture user634175 · Sep 1, 2012

Only the first file is used as the main template. The other template files need to be included from the first like so:

Title is {{.Title}}
{{template "footer.html" .}}

The dot after "footer.html" passes the data from Execute through to the footer template -- the value passed becomes . in the included template.