There are two possible approaches:
- With “Dangling” HTML tags.
- Layout Page
1. With “Dangling” HTML tags
First, the layout-parts.gohtml is created:
├── templates
│ ├── contact.gohtml
│ ├── faq.gohtml
│ ├── fs.go
│ ├── home.gohtml
│ └── layout-parts.gohtml
This is how the home.gohtml looks:
{{template "header"}}
<h1>Welcome to my awesome site!</h1>
{{template "footer"}}
This is how the layout-parts.gohtml looks:
{{{define "header"}}}
<html>
<body>
{{end}}
{{define "footer"}}
<p>Copyright Alex Escobar 2023</p>
</body>
</html>
{{end}}
And, the only change that main.go requires is to add the layout-parts.gohtml here:
r.Get("/", controllers.StaticHandler(views.Must(views.ParseFS(templates.FS, "home.gohtml", "layout-parts.gohtml"))))
Both .gohtml files will be rendered since the function accepts variadic (…) parameters.
2. Layout Page
├── templates
│ ├── contact.gohtml
│ ├── faq.gohtml
│ ├── fs.go
│ ├── home.gohtml
│ └── layout-parts.gohtml
│ └── layout-page.gohtml
This is how the home.gohtml looks:
{{define "page"}}
<h1>Welcome to my awesome site!</h1>
{{end}}
This is how the layout-page.gohtml looks:
<html>
<body>
{{template "page"}}
<p>Copyright Alex Escobar 2023</p>
</body>
</html>
And, the only change that main.go requires is to add the layout-parts.gohtml here:
r.Get("/", controllers.StaticHandler(views.Must(views.ParseFS(templates.FS, "layout-page.gohtml", "home.gohtml"))))
NOTES
- The course uses “Dangling” HTML tags.
- Personally, I do prefer the “Layout page” approach. I believe I have seen in when doing changes in HUGO (static site generator).
- Remember how things are being rendered, left to right by views.ParseFS function.