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.
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.