How do you use Go 1.16 embed features in subfolders/packages?

I finally figured it out…

You can keep the templates folder in the main folder and embed them from there. Then you need to inject the FS variable into the other handler package. It’s always easy after you figure it out.

e.g.

package main

//go:embed templates/*
var templateFs embed.FS

func main() {
    handlers.TemplateFs = templateFs
...
package handlers

var TemplateFs embed.FS

func handlerIndex() {
    ...
    tmpl, err = tmpl.ParseFS(TemplateFs, "templates/layout.gohtml",...
...

Leave a Comment