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 acceptsHomeData. Pass anything else and the program does not compile.
What templator gives you
Section titled “What templator gives you”- Compile-time data safety.
Handler[T]executes with typeTor not at all. Missing fields, wrong types, and copy-paste data mistakes are caught by the compiler. - 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. fs.FS-based template management. Templates load lazily and are cached in a concurrent-safe registry — from disk, fromembed.FS, or from an in-memory filesystem in tests.- Context-aware execution.
Executetakes acontext.Context, checks it before rendering, on every write, and after rendering. - Typed accessors via
go:generate. An optional generator turnstemplates/components/header.htmlintotpl.GetComponentsHeader()so template names survive refactors.
Everything stays on html/template: contextual auto-escaping, custom
functions, and template syntax are all standard.
Where to start
Section titled “Where to start”- New to templator? Do the Quickstart — it is one struct, one template file, and two calls.
- Want the reasoning first? Read the type-safety model.
- Writing tests? Jump to test templates.
- All signatures and error types: the API reference.