0

In this code, I made a base.html file to stop the repetition of the HTML code in each file. I used the {{define ".."}} and {{template ".." .}} properly in both home.html and about.html.

But when I run the code, and visit localhost:8080 or localhost:8080/about, it only gives the result of the home.html file. Although for the /about link, it should give the result of the about.html file.

main.go

func main() {
    http.HandleFunc("/", handler.Home)
    http.HandleFunc("/about", handler.About)
    fmt.Println("Starting the server at :8080")
    http.ListenAndServe(":8080", nil)
}

handler.go

func init() {
    tmpl = template.Must(template.ParseGlob("templates/*.html"))
}

func Home(w http.ResponseWriter, r *http.Request) {
    tmpl.ExecuteTemplate(w, "home.html", nil)
}

func About(w http.ResponseWriter, r *http.Request) {
    tmpl.ExecuteTemplate(w, "about.html", nil)
}

base.html

{{define "base"}}

<!DOCTYPE html>
<html lang="en">
<head>
    <title>{{template "title" .}}</title>
</head>
<body>
    <section>
        {{template "body" .}}
    </section>
</body>
</html>

{{end}}

home.html

{{template "base" .}}

{{define "title"}} Home page {{end}}

{{define "body"}} 
    <h1>Home page</h1>
    <p>This is the home page</p>
{{end}}

about.html

{{template "base" .}}

{{define "title"}} About page {{end}}

{{define "body"}} 
    <h1>About page</h1>
    <p>This is an about page</p>
{{end}}
  • You need to show how you register your HTTP handlers. – Marc Aug 11 '21 at 07:36
  • 1
    This question have already been answered here : https://stackoverflow.com/questions/11467731/is-it-possible-to-have-nested-templates-in-go-using-the-standard-library – Uday Yadav Aug 11 '21 at 08:15

1 Answers1

2

Use must create your templates separately, for each page include base.html and page.html:

var tmpl = make(map[string]*template.Template)

func init() {
    tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))
    tmpl["about"] = template.Must(template.ParseFiles("templates/about.html", "templates/base.html"))
}

func Home(w http.ResponseWriter, r *http.Request) {
    tmpl["home"].ExecuteTemplate(w, "home.html", nil)
}

func About(w http.ResponseWriter, r *http.Request) {
    tmpl["about"].ExecuteTemplate(w, "about.html", nil)
}
alexmac
  • 19,087
  • 7
  • 58
  • 69
  • I implemented the code, but it is loading no page. – sikandar meranam Aug 11 '21 at 08:57
  • @sikandarmeranam could you share your updated code (create github gist or similar)? – alexmac Aug 11 '21 at 09:38
  • I wrote all the functions in `main.go` and removed the functions in `handler.go` and it worked but when I write the functions in `handler.go`, and call them in the main function, it does not work. Although I call the functions like this `handler.Home` – sikandar meranam Aug 11 '21 at 09:53