I am using gin gonic and it's features. One if them being html template rendering.
So in spirit of DRY I wanted to create a base.html
template with all common html tags etc. with a
slot for different page bodies.
In essence, this is the base.html
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
{{ template "main" . }}
</body>
</html>
{{end}}
Then I created a "child" template called home.html
:
{{template "base" .}}
{{define "main"}}
<div class="container mt-5">
Hello
</div>
{{end}}
I followed this wonderful guide on this page and it worked like a charm.
The problem
But when I tried adding another page with different body in subpage.html
eg:
{{template "base" .}}
{{define "main"}}
<div class="container">
<div>
<h2>This page is still in progress</h2>
</div>
</div>
{{end}}
the last template that is picked by gins LoadHTMLFiles
or LoadHTMLGlob
, is then displayed on every page. In this case this is subpage.html
content.
How do I fix this. Is it even possible to achieve this behaviour by default?
LoadHTMLFiles
/LoadHTMLGlob
that parses all the files together and relies on the uniqueness of their names to know which one you want to render, you would parse each page-specific template file together with its dependencies but separate from other page-specific template files, this way you end up with one*template.Template
object per each page handler and you then execute that template object from its corresponding handler. – mkopriva