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