Go HTML Templates

I'm working on a music scrobbler and decided to use regular degular HTML (by way of HTMX). This prompted me to dive into the stdlib's template system instead of reaching for something like Templ. Here are a view things I learned along the way.

{{ define "content" }} tag

This denotes the creation of a template. Whatever is between these tags belongs to that template. dit's important to note that you can continuously redefine templates. This comes in handy when nesting templates.

{{ template "content" .}} tag

This denotes that the template named "content" should be placed here. The . is for passing the data in the current file to the template. This will break the template when executing if the "content" template is referencing data at all if it is missing. Seems safer to just always pass it.

{{ block "content" .}} tag

This is syntactic sugar for defining and placing a template at the same time. It's the equivalent to:

{{ template "content" .}}
{{ define "content" }}
<p>Hello World</p>
{{end}}

Putting it all together

{{define "base"}}
<body>
  <header>
    {{template "header" .}}
  </header>
  {{template "content" .}}
  <footer>
    <p>Made by Mente</p>
  </footer>
</body>
{{end}}

base.html

💡
This defines a "base" template that uses the "header" and "content" template within it
{{template "base" .}}

{{define header}}
<h1>Intro</h1>
<span>Welcome to my page</span>
{{end}}

{{define "content"}}
<p>This is content about the Intro page</p>
<p>Another paragraph about the intro page</p>
{{end}}

intro.html

💡
This adds the "base" template into the file. Since we also define "header" and "content" here, this will be what is populated into the placeholders found in "base".
package main

import (
  "os"
  "html/template"
)

tmpl := template.Must(template.ParseFiles("intro.html", "base.html"))
tmpl.Execute(os.Stdout, nil)

main.go