Skip to content

Quickstart

In this quickstart you render templates/home.html with data that is checked by the compiler. Every line below is the complete, real API.

  • Go 1.26 or newer (the version declared in templator’s go.mod).
Terminal window
go get github.com/alesr/templator@latest

The optional accessor generator is a separate binary, installed on demand in Generate typed accessors.

templates/
home.html
<h1>{{.Title}}</h1>
<p>{{.Content}}</p>

The directory templates is the default location (constant templator.DefaultTemplateDir). You can point the registry elsewhere with WithTemplatesPath.

This struct is the contract for every template in your registry:

type HomeData struct {
Title string
Content string
}
package main
import (
"context"
"log"
"os"
"github.com/alesr/templator"
)
func main() {
fs := os.DirFS(".")
reg, err := templator.NewRegistry[HomeData](fs)
if err != nil {
log.Fatal(err) // never returns an error today; see the API reference
}
home, err := reg.Get("home")
if err != nil {
log.Fatal(err) // template file missing or unparsable
}
err = home.Execute(context.Background(), os.Stdout, HomeData{
Title: "Welcome",
Content: "Hello, World!",
})
if err != nil {
log.Fatal(err)
}
}

Run it:

<h1>Welcome</h1>
<p>Hello, World!</p>

Now try passing the wrong data type to Execute:

home.Execute(ctx, w, AboutData{Company: "acme"}) // does not compile

That is the whole idea: html/template would fail on this at runtime; templator moves the failure to go build.