How to Use Embedded Templates in Go

Use the embed package with //go:embed directives to compile template files directly into your Go binary for single-file distribution.

Use the embed package to compile template files directly into your binary at build time. Define a variable with the //go:embed directive pointing to your template directory, then parse the files from the embedded FS into a template.Template object.

package main

import (
	"embed"
	"html/template"
	"log"
	"os"
)

//go:embed templates/*.html
var templatesFS embed.FS

func main() {
	tmpl, err := template.ParseFS(templatesFS, "templates/*.html")
	if err != nil {
		log.Fatal(err)
	}
	if err := tmpl.ExecuteTemplate(os.Stdout, "index.html", nil); err != nil {
		log.Fatal(err)
	}
}