Go templates are still a {{ block “er” . }}

Templating was not where I anticipated getting stuck in Go. I have so much experience with Hugo! Hugo does a lot of the dirty work though, and my mental model is just not yet there with Go templates and the html/template package API.

While on a Reddit post about templates, I discovered my init functions to load the templates were unnecessary.

Before:

var tmpl *template.Template

func init() {
tmpl = template.Must(template.ParseFS(assets.TmplFiles, "templates/*.html"))
}

After:

var tmpl = template.Must(template.ParseFS(assets.TmplFiles, "templates/*.html"))

I had originally tried tmpl := template.Must() outside of a function body, but the compiler threw a fit. It turns out than the non-walrus variable assignment works just fine outside of function bodies. Go figure.

My biggest blocker on Go templates is {{ block "name" }}. It doesn’t seem to behave the way I remember from Hugo.

I also saw this interesting piece of code in a Discourse post about templates:

t := template.Must(template.ParseGlob("./web/templates/*.go.tmpl"))
t = template.Must(t.ParseGlob("./web/templates/components/*.go.tmpl"))
t = template.Must(t.ParseGlob("./web/templates/pages/*.go.tmpl"))

It seems that you can use all template functions on an instance of template (t in this case). It seems like this is a way to ensure that template parts load in the correct order.

Also, according to this Stack Overflow answer, the template’s Clone method is a good way for sharing partial templates.

baseTemplate, err = template.ParseFiles(
"views/layout/base.gohtml",
"views/layout/menu.html",
"views/layout/footer.gohtml")
if err != nil {
panic(err)
}

homeTemplate, err = template.Must(baseTemplate.Clone()).ParseFiles("views/home.gohtml")
if err != nil {
panic(err)
}

contactTemplate, err = template.Must(baseTemplate.Clone()).ParseFiles("views/contact.gohtml")
if err != nil {
panic(err)
}

This all feels so complicated compared to raw PHP, Blade, EJS, Jinja2, Django Templates, Twig, ERB, etc. The only templating language I’ve ever gotten stuck on before this… was also Go templates while using Hugo. But at least that abstracted away the html/template madness from me.

I’ll get there, but I know I’m not there yet.

Anyway, I’ll figure out how to work with the block directive works soon. I’d like to think that things will get easier after that, but they sure haven’t yet.

That said, I’ve figured out React, Docker, Jenkins, Rails, XState, etc. I can figure this out too.

Leave a comment