I am trying to change contents dynamically. But the content remains the same. Seems to fetch first match. no matter what the template is. Does not work even with hardcoded file names. The code works as expected but the content cannot be changed.
Main layout
{{define "layout"}}
<html>
<body>
{{ template "content" }}
</body>
</html>
{{end}}
Sub template 1
{{ define "content" }}
<h1 style="color: red;">Page 1!</h1>
{{ end }}
Sub template 2
{{ define "content" }}
<h1 style="color: blue;">Page 2!</h1>
{{ end }}
The Go code
package main
import (
"html/template"
"net/http"
"strings"
)
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}
func main() {
http.HandleFunc("/", index)
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
path := strings.Trim(r.URL.Path, "/")
switch path {
case "":
path = ("index.gohtml")
default:
path = (path + ".gohtml")
}
err := tpl.ExecuteTemplate(w, "layout", path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
I have also tried to ParseFiles before Execute with no luck. What am I doing wrong?