21

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.

deft_code
  • 57,255
  • 29
  • 141
  • 224
Tech163
  • 4,176
  • 8
  • 33
  • 36

2 Answers2

31

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.

Tech163
  • 4,176
  • 8
  • 33
  • 36
23

There is a little shortcoming in user634175's method: the {{template "footer.html" .}} in the first template must be hard coded, which makes it difficult to change footer.html to another footer.

And here is a little improvement.

header.html:

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

footer.html:

{{define "footer"}}Body is {{.Body}}{{end}}

So that footer.html can be changed to any file that defines "footer", to make different pages

Melkor
  • 532
  • 8
  • 25
Mingliang
  • 799
  • 6
  • 12