Kits

Go types and funcs

Register the Go types components bind with kit.Types, add template functions with kit.Funcs, and check such a kit from Go, since the CLI cannot load it.

Most of a kit is files. Two things can only come from Go: the types of the values components bind, and extra template functions. Both are options to kit.Load, and both are checked like everything else: a kit template that misuses a bound type or a function fails at load.

Register a type

A kit that binds Go values lists their type names in kit.yaml:

tutorial/kit/kit.yaml#L10-L12
# Go types components may bind. The kit's Go package registers each one
# with kit.Types, so this kit loads from Go, not from the CLI.
types: [Invoice]

The kit's Go package defines the types. The tutorial's Invoice holds its lines and total, and Money formats itself:

tutorial/tutorial.go#L14-L48
// Money is an amount in cents.
type Money int64

// String formats m in dollars, such as "$1250.00". Merge tags and kit
// templates both print a Money through it.
func (m Money) String() string {
    sign := ""
    if m < 0 {
        sign, m = "-", -m
    }
    return fmt.Sprintf("%s$%d.%02d", sign, m/100, m%100)
}

// Line is one line of an invoice.
type Line struct {
    Name   string
    Qty    int
    Amount Money // the line total
}

// Invoice is the Go type the kit's invoice component binds. kit.yaml lists
// it under `types`, and Kit registers it under the same name.
type Invoice struct {
    Number string
    Lines  []Line
    Total  Money
}

// Data is the data of templates/invoice.md. Merge tags such as
// {{invoice.number}} and the :invoice="invoice" binding resolve against it.
type Data struct {
    Invoice Invoice `json:"invoice"`
    Due     string  `json:"due"`
    PayURL  string  `json:"pay_url"`
}

Then it registers each listed name when it loads the kit:

tutorial/tutorial.go#L64-L70
// LoadKit loads the tutorial kit from fsys (a copy of kit/ on disk, say)
// with the Go types its components bind. A kit with `types` in kit.yaml
// loads only with every listed type registered. Kit() is
// LoadKit(Files()) cached.
func LoadKit(fsys fs.FS) (*kit.Kit, error) {
    return kit.Load(fsys, kit.Types(kit.TypeOf[Invoice]("Invoice")))
}
  • kit.TypeOf[T](name) returns a kit.TypeDef registering T under name. kit.Types(defs...) passes them to Load.
  • Names are identifiers, each registered once. Every name in kit.yaml's types must be registered, or Load reports types: "Invoice" is not registered at its position.
  • Any Go type works: structs, named scalars such as Money, and slices. Quiet registers kit.TypeOf[[]StockItem]("StockItems") so a component can bind a plain slice.

Bind the type in a component

A component names the registered type in its bindings, here invoice: { type: Invoice, required: true }:

tutorial/kit/components/invoice/component.yaml
# An invoice: the bound Invoice's lines, then its total. A template
# passes the invoice with a binding: ::invoice{:invoice="invoice"}.
name: invoice
attrs:
  title: { type: text, default: Invoice }
bindings:
  invoice: { type: Invoice, required: true }
content: none
spacing:
  top: size.block
  bottom: size.gap

The template passes a value from its data with :key="path". The tutorial's data type has an Invoice field under the JSON name invoice:

tutorial/templates/invoice.md
---
template: invoice
profile: billing
subject: "Invoice {{invoice.number}}"
preheader: "{{invoice.total}} due by {{due}}."
---

# Your invoice

Hi {{name | there}}, here is invoice {{invoice.number}} for September.

::invoice{:invoice="invoice"}
::

::section
Please pay by {{due}} to keep your plan active.

:button[Pay {{invoice.total}}]{href="{{pay_url}}"}
::

::footer{note="Questions about this invoice? Reply to this email."}
::

In the component's templates, .Bind.invoice is then an Invoice. Fields and methods are checked at load, and a value prints through its String method: {{.Bind.invoice.Total}} renders $76.00. The text form calls the method explicitly, to pass a string to leader:

tutorial/kit/components/invoice/text.tmpl
{{- /* The invoice as dot leaders. leaders lines its rows up in one
column; each row here is its own call, since a template cannot collect
rows in a loop, and short labels share the same column anyway. */ -}}
{{upper .Attrs.title}} {{.Bind.invoice.Number}}

{{range .Bind.invoice.Lines -}}
{{leaders (leader (printf "%s x%d" .Name .Qty) .Amount.String)}}
{{end -}}
{{leaders (leader "Total" .Bind.invoice.Total.String)}}

The bound value must have exactly the registered type. These are compile errors from lttr.Compile against the tutorial kit, each from invoice.md above with one change to line 12:

TemplateError
::invoice with no bindinginvoice:12:1: invoice: missing binding ":invoice"
::invoice{:invoice="due"}, a string fieldinvoice:12:1: invoice: :invoice is string, want tutorial.Invoice
Unchanged, but compiled as map[string]anyinvoice:12:1: invoice: :invoice is untyped data (invoice), want tutorial.Invoice

Untyped data can fill merge tags, but never a binding. See Merge tags and data.

Add template functions

kit.Funcs adds functions to every kit template: HTML, text and styles.css. The renderer installs the same functions when it renders. Use them for what templates cannot express, such as formatting or choosing a word; keep the markup in the templates.

main.go
package main

import (
    "fmt"
    "log"
    "os"

    "github.com/sulv-io/lttr/kit"
)

// Money, Line and Invoice are the Go values the kit's invoice component
// binds; kit.yaml lists Invoice under `types`.
type Money int64

func (m Money) String() string { return fmt.Sprintf("$%d.%02d", m/100, m%100) }

type Line struct {
    Name   string
    Qty    int
    Amount Money
}

type Invoice struct {
    Number string
    Lines  []Line
    Total  Money
}

// plural is an extra template function: {{plural .Qty "seat" "seats"}}.
func plural(n int, one, many string) string {
    if n == 1 {
        return one
    }
    return many
}

func main() {
    k, err := kit.Load(os.DirFS("emailkit"),
        kit.Types(kit.TypeOf[Invoice]("Invoice")),
        kit.Funcs(map[string]any{"plural": plural}),
    )
    if err != nil {
        log.Fatal(err) // every problem, each with its kit file position
    }
    fmt.Printf("loaded %s: %d components\n", k.Name(), len(k.Components()))
}
  • A function returns one value, or a value and an error. A non-nil error is a render error at the call, like any core function's.
  • Calls are type-checked against the Go signature. With plural registered, (plural .Name "seat" "seats") in the invoice's text form fails at load: components/invoice/text.tmpl:7:58: plural: argument 1 is string, want int.
  • Names must be identifiers and must not collide with a core function (kit.CoreFuncNames()) or a text/template builtin.
  • Load never runs them. The type check reads their signatures, and the escape check executes stand-ins.

A bad registration is a load error with no file position:

kit.Load error
funcs: "len" collides with a template builtin
funcs: "token" collides with a core function
funcs: "two" must return one value, or a value and an error

Know why the CLI cannot load them

The CLI loads a kit directory with no Go options: it has no Go types and no functions for it. A kit that lists types, or calls a function from kit.Funcs, fails to load there, and the CLI says so:

Terminal
$ lttr kit check examples/tutorial/kit
examples/tutorial/kit/kit.yaml:12:9: types: "Invoice" is not registered
examples/tutorial/kit: kit directories load without Go types; check kits that bind Go types from Go (see README)
Terminal
$ lttr kit check ./emailkit
emailkit/components/section/text.tmpl:1: function "money" not defined
./emailkit: kit directories load without Go template functions (kit.Funcs); check kits that add functions from Go (see README)

So lttr kit check, lint, preview and serve cannot show such a kit from its directory. Check it from Go instead.

Check a typed kit from Go

Test the kit in its own package: load it with its options, then compile and render every template with typed data and lint the HTML. The lint package does the compiling, rendering and linting over an lttr.SampleSet, which holds the kit, the Config to render with and the samples. The tutorial's package describes its invoice template that way, with the billing profile the template uses and typed sample data:

tutorial/tutorial.go#L105-L139
// Set returns the tutorial as a sample set: the kit, a Config with the
// "billing" profile the template names, and the invoice template with
// typed sample data, rendered for ada@example.com.
func Set() *lttr.SampleSet {
    k := MustKit()
    return &lttr.SampleSet{
        Kit: k,
        Config: lttr.Config{
            Kit: k,
            Profiles: []lttr.Profile{{
                Name: "billing",
                From: mail.Address{Name: "Example Billing", Address: "billing@example.com"},
            }},
        },
        Samples: []lttr.Sample{
            lttr.NewSample("invoice.md", invoiceSource, sampleInvoice(), lttr.Recipient{Address: "ada@example.com", Name: "Ada"}),
        },
    }
}

// sampleInvoice is the data the tutorial's invoice is shown with.
func sampleInvoice() Data {
    return Data{
        Invoice: Invoice{
            Number: "INV-0042",
            Lines: []Line{
                {Name: "Team plan, September", Qty: 1, Amount: 4900},
                {Name: "Extra seats", Qty: 3, Amount: 2700},
            },
            Total: 7600,
        },
        Due:    "9 October",
        PayURL: "https://example.com/billing/INV-0042",
    }
}

lint.Check returns every compile, render and lint problem of the set, each with its file position. A render error names the Markdown position and the kit file position:

tutorial/tutorial_test.go#L17-L42
// TestCheck runs lint.Check over the tutorial's sample set (Set): the
// invoice, with its typed data, compiles, renders and lints clean.
func TestCheck(t *testing.T) {
    for _, p := range lint.Failures(lint.Check(Set())) {
        t.Error(p) // file:line:col: message
    }
}

// TestSamples checks the kit's samples/*.md with their data from
// samples.yaml: lint.Check compiles and renders each one and lints the
// HTML. `lttr kit check` does this for a kit that loads without Go types;
// this kit binds Invoice, so its samples are checked here instead.
func TestSamples(t *testing.T) {
    set, err := lttr.KitSamples(MustKit(), lttr.Config{
        Profiles: []lttr.Profile{{Name: "default", From: mail.Address{Address: "hello@example.com"}}},
    })
    if err != nil {
        t.Fatal(err)
    }
    if len(set.Samples) == 0 {
        t.Fatal("the kit has no samples")
    }
    for _, p := range lint.Failures(lint.Check(set)) {
        t.Error(p)
    }
}

TestSamples checks the kit's own samples/*.md too, which lttr kit check would do for an untyped kit. lttr.KitSamples builds that set from samples/ and samples/samples.yaml; the data comes from YAML, so it is untyped (map[string]any). lint is a public package, so this test works unchanged in your own module. See Goldens and testing and Email-safe HTML.

Next steps

Copyright © 2026