Skip to content

templator

Type-safe HTML templating for Go — catch data errors at compile time, not in production.

templator is a thin, type-safe wrapper around Go’s standard html/template package. You keep writing plain .html template files; templator makes the data you pass to them a compile-time contract. The source code lives at github.com/alesr/templator (MIT).

type HomeData struct {
Title string
Content string
}
reg, _ := templator.NewRegistry[HomeData](fs)
home, _ := reg.Get("home")
err := home.Execute(ctx, w, HomeData{Title: "Welcome"})

The two lines that matter:

  • NewRegistry[HomeData] binds an entire registry of templates to one data type.
  • home.Execute(ctx, w, data) only accepts HomeData. Pass anything else and the program does not compile.
  1. Compile-time data safety. Handler[T] executes with type T or not at all. Missing fields, wrong types, and copy-paste data mistakes are caught by the compiler.
  2. Optional load-time field validation. Enable WithFieldValidation(HomeData{}) and templator checks, when a template is first loaded, that every field it references (like {{.Title}}) exists in the data type.
  3. fs.FS-based template management. Templates load lazily and are cached in a concurrent-safe registry — from disk, from embed.FS, or from an in-memory filesystem in tests.
  4. Context-aware execution. Execute takes a context.Context, checks it before rendering, on every write, and after rendering.
  5. Typed accessors via go:generate. An optional generator turns templates/components/header.html into tpl.GetComponentsHeader() so template names survive refactors.

Everything stays on html/template: contextual auto-escaping, custom functions, and template syntax are all standard.