Template checking
kit.Load does not stop at parsing. It type-checks every template in the kit against the view it executes with, so a typo in a field, an attribute, a token or a function call fails when the kit loads, with its position in the kit file. It never waits for the first email that happens to reach that line.
Catch a typo at load
The tutorial's invoice template reads the bound Invoice through .Bind.invoice:
{{- /* The title and number, one row per line (name, quantity, amount),
then the total. .Bind.invoice is an Invoice, so every field below is
checked against the Go type when the kit loads. */ -}}
<tr><td class="pl-px" align="left" style="padding:{{px .Section.Top}} {{token "size.side"}}px {{px .Section.Bottom}};">
<p class="pl-text" style="margin:0 0 8px;{{style "font-family" "font.sans"}}font-size:{{token "size.h2"}}px;line-height:{{token "size.h2_line"}}px;font-weight:600;{{style "color" "color.text"}}">{{.Attrs.title}} {{.Bind.invoice.Number}}</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;">
{{- range .Bind.invoice.Lines}}
<tr><td class="pl-text pl-rule" align="left" style="padding:10px 0;{{style "border-bottom" (printf "1px solid %s" (token "color.border"))}}{{style "font-family" "font.sans"}}font-size:{{token "size.text"}}px;line-height:{{token "size.line"}}px;{{style "color" "color.text"}}">{{.Name}}</td>
<td class="pl-muted pl-rule" align="right" style="padding:10px 0 10px 12px;{{style "border-bottom" (printf "1px solid %s" (token "color.border"))}}{{style "font-family" "font.sans"}}font-size:{{token "size.text"}}px;line-height:{{token "size.line"}}px;{{style "color" "color.muted"}}white-space:nowrap;">× {{.Qty}}</td>
<td class="pl-text pl-rule" align="right" style="padding:10px 0 10px 12px;{{style "border-bottom" (printf "1px solid %s" (token "color.border"))}}{{style "font-family" "font.sans"}}font-size:{{token "size.text"}}px;line-height:{{token "size.line"}}px;{{style "color" "color.text"}}white-space:nowrap;">{{.Amount}}</td></tr>
{{- end}}
<tr><td class="pl-text" colspan="2" align="left" style="padding:10px 0 0;{{style "font-family" "font.sans"}}font-size:{{token "size.text"}}px;line-height:{{token "size.line"}}px;font-weight:600;{{style "color" "color.text"}}">Total</td>
<td class="pl-text" align="right" style="padding:10px 0 0 12px;{{style "font-family" "font.sans"}}font-size:{{token "size.text"}}px;line-height:{{token "size.line"}}px;font-weight:600;{{style "color" "color.text"}}white-space:nowrap;">{{.Bind.invoice.Total}}</td></tr>
</table>
</td></tr>
Misspell .Bind.invoice.Total on line 13 as .Bind.invoice.Totl, and the kit does not load:
components/invoice/html.tmpl:13:243: Invoice has no field or method "Totl"
The checker knows .Bind.invoice is an Invoice because the schema binds invoice: { type: Invoice } and Go registered Invoice under that name. The position is the line and the byte column of the typo. The tutorial pins this exact error in a test, so the docs and the code fail together if either changes:
// TestTypo: a misspelt field on a bound type fails kit.Load, with the
// position of the typo in the kit file.
func TestTypo(t *testing.T) {
overlay := fstest.MapFS{}
err := fs.WalkDir(Files(), ".", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
b, err := fs.ReadFile(Files(), path)
if err != nil {
return err
}
overlay[path] = &fstest.MapFile{Data: b}
return nil
})
if err != nil {
t.Fatal(err)
}
const tmpl = "components/invoice/html.tmpl"
src := string(overlay[tmpl].Data)
if !strings.Contains(src, ".Bind.invoice.Total") {
t.Fatalf("%s no longer shows .Bind.invoice.Total", tmpl)
}
overlay[tmpl].Data = []byte(strings.Replace(src, ".Bind.invoice.Total", ".Bind.invoice.Totl", 1))
_, err = load(overlay)
const want = `components/invoice/html.tmpl:13:243: Invoice has no field or method "Totl"`
if err == nil || err.Error() != want {
t.Errorf("load error = %v\nwant %s", err, want)
}
}
Know what Load checks
kit.Load runs every check and reports every problem it finds, not just the first:
- YAML. Every key of
kit.yamland eachcomponent.yamlis known, every value has the right type, names are valid, token values are CSS-safe, and attribute rules agree with each other. - References.
default,children,must_followandspacing.aftername real components or classes. Aliases are unique. Everytypesentry is registered, and every binding names a listed type. - Files and defines.
layout.html,layout.txt,styles.css,blocks.htmland each component'shtml.tmplexist.blocks.htmldefines every block the kit needs. - Parsing. Every template parses, with every function it calls known.
- Escaping.
html/template's contextual escaper runs over every HTML template, so an action in a context it cannot escape (an unclosed attribute, say) fails now, not at the first render. - Types. Every template is walked with the static type of its dot, as below.
The type check follows the dot through with, range (over slices, arrays, maps and integers), if, variables and {{template "name" .}} calls, and checks:
- Field and method chains on the views and on bound Go types, including methods such as
.Amount.String. - Schema keys:
.Attrs.x,.Bind.xand.Doc.Front.xmust be declared by the component's schema orkit.yaml, and each is typed from it. A child's.Attrsand.Bindare typed by the child's schema. Anhtmlattribute istemplate.HTMLinhtml.tmplandstringintext.tmpl. Literal keys given toindexare checked too. An unknown key gets the closest declared one as a suggestion. - Function calls: the number and types of the arguments of every core function and every
kit.Funcsfunction. - Literal names: the string argument of
token,darkandvarmust name a token or var, with a suggestion when one is close.tokensuggests only tokens with a light value, anddarkonly tokens with a dark value. A literal value given tostylethat reads as a token name (dotted lower-case segments, such ascolor.txt, whose first segment is the group of one of the kit's tokens) must be a token with a light value too. CSS values such as0.5em,rgb(0 0 0 / .5)or a font stack never read as one. - Ranges and templates:
rangeover something that cannot be ranged, and calls to templates that do not exist.
Read the errors
Every error has the form path:line:col: message, with a path relative to the kit root and a 1-based byte column. Parse errors carry a line only. kit.Load sorts them by file and position, drops duplicates, stops at 50 per file (then N more errors) and returns them joined with errors.Join, each a *kit.Error with Path, Line, Col and Msg.
These come from lttr kit check, each on a copy of Plain with one mistake. The CLI puts the kit directory in front of each path:
| Mistake | Error |
|---|---|
| A misspelt token | emailkit/components/section/html.tmpl:1:179: token: unknown token "size.txt" (did you mean size.text?) |
A misspelt token in style | emailkit/components/section/html.tmpl:1:247: style: unknown token "color.txt" (did you mean color.text?) |
| A misspelt var | emailkit/components/footer/html.tmpl:4:188: var: unknown var "compnay" (did you mean company?) |
| An attribute the schema does not declare | emailkit/components/button/html.tmpl:2:496: unknown key "lable" in Attrs (did you mean label?) |
A string where px wants an int | emailkit/components/button/html.tmpl:1:56: px: argument 1 is "12", want int |
range over a text attribute | emailkit/components/button/html.tmpl:2:496: range over string |
| A function that does not exist | emailkit/components/section/text.tmpl:1: function "money" not defined |
| A block define removed while a component allows images | emailkit/blocks.html: missing define "image" |
| An attribute left open at the end of a define | emailkit/blocks.html: ends in a non-text context: {stateAttr delimDoubleQuote urlPartNone jsCtxRegexp [] attrNone elementNone <nil>} |
The last one is html/template's own escaping error, raised at load: the inline define had become <b title="{{.HTML}}.
Know the limits
The checker is conservative. It reports only what it can prove, so some mistakes pass it:
- Interfaces are untyped. A value whose static type is an interface,
anyincluded, stops the check along that chain without an error..Contentis an interface, but it only goes tocontent. Bound Go types are concrete, so they are checked in full. - A variable reassigned to a value of a different type becomes untyped.
- Computed names passed to
token,darkorvarare checked when they render, not at load. - Grandchildren read inline are checked against the child's schema, not the grandchild's: in any template,
ChildAttrsandChildBindare typed by that component's direct children. A key the child also declares passes the check and can fail at render. Reach grandchildren throughrenderinstead. See Render nested components. - Three cases pass the check and fail at render: a method on
*Treached through a value that is not addressable (a map element, anindexresult), a method with no results, andrange $i, $jover an int or aniter.Seq.
Values are never known at load either. An index out of range, a nil pointer inside a bound value, a URL that fails its check, an unsafe style value, or a fail all surface when a template renders. They carry the Markdown position and the kit position, so they are still easy to find:
$ lttr kit check ./emailkit
emailkit/samples/welcome.md:16:1: button: emailkit/components/button/text.tmpl:1:3: error calling index: index out of range: 99
lttr kit check: ./emailkit: 1 problem
lttr kit check, and your own tests, render every sample, which is how these are caught before a real send. See Go types and funcs for a kit the CLI cannot load.
Next steps
- Go types and funcs: register the types the checker follows.
- Compile errors: the errors a Markdown template gets when it breaks a schema.
Templates and views
The kit's templates, the typed view each one executes with, and every core template function, with its signature.
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.