Multiple files using template.ParseFiles in golang

13,381

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

Share:
13,381

Related videos on Youtube

Tech163
Author by

Tech163

Updated on June 14, 2020

Comments

  • Tech163
    Tech163 almost 3 years

    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.

Related