Multiple files using template.ParseFiles in golang
Asked Answered
K

2

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.

Koroseal answered 1/9, 2012 at 2:30 Comment(0)
B
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.

Barris answered 1/9, 2012 at 15:41 Comment(1)
This seems to be exactly what I was looking for. Thanks!Koroseal
V
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

Vasoconstrictor answered 4/12, 2012 at 7:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.