componentsI have an app in which I am trying to use multiple templates derived from a base layout.
The templates load ok when the app launch but when I navigate to the app it is either:
base.tmpl.html
{{define "base"}}
<html>
<head>
some title
</head>
<body>
{{ template "content" . }}
</body>
<footer>
{{ template "footer" . }}
</footer>
</html>
{{end}}
footer.tmpl.html
{{define "footer"}}
<h1>Footer</h1>
{{end}}
home.tmpl.html - This is the page I am trying to render.
{{ define "content" }}
<h1>test</h1>
{{ end }}
This is the route. When I specify "content" I get 'test' within the h1 tags but without the footer or 'some title' from the base. When I specify home.tmpl.html
the view is blank.
There are no errors generated for either and the responses return 200 OK.
func GetIndex(c *gin.Context) {
c.HTML(http.StatusOK, "content", gin.H{
"title": "Home Page",
})
}
I am loading the templates like so:
func main() {
router := setupRouter()
router.Run()
}
func setupRouter() *gin.Engine {
router := gin.Default()
files, err := filepath.Glob("templates/*")
if err != nil {
log.Fatal(err)
}
tmpl := template.Must(template.New("").ParseFiles(files...))
router.SetHTMLTemplate(tmpl)
router.StaticFS("/static", http.Dir("static"))
router.SetTrustedProxies([]string{"*"})
routes.InitializeRoutes(&router.RouterGroup)
return router
}
The following setup resolved the issue
Rename base.tmpl.html
to base.layout.tmpl
{{define "base"}}
<html>
<head>
some title
</head>
<body>
{{block "content" .}}
{{end}}
</body>
{{template "footer" .}}
</html>
{{end}}
home.tmpl.html
{{template "base" .}}
{{define "content"}}
<h1>test</h1>
{{ end }}
footer.tmpl.html
{{define "footer"}}
<footer>
<h1>Footer</h1>
</footer>
{{end}}