API reference
A map of the public surface at v0.2.0, copied from go doc -all and grouped by package. Each section links to the page that explains it in context.
Most services import the root package and one kit: kits/plain, kits/quiet or a kit package of their own, which uses kit to load its files. Their tests import lint, the HTML lint and golden-file checks behind lttr lint and lttr kit check. data holds Recipient and the path rules merge tags follow. render and ir matter for their error types. The other packages, comark, render/html and render/text, are stages of the pipeline, exported for tools. internal/tmplcheck (the kit template checker) and internal/suggest (the "did you mean" matcher) are internal and can't be imported from outside the module.
Import lttr
import "github.com/sulv-io/lttr"
Compile templates against a kit, render messages, and send them.
Compile templates
func Compile[T any](k *kit.Kit, name string, src []byte) (*Template[T], error)
func MustCompile[T any](k *kit.Kit, name string, src []byte) *Template[T]
type Template[T any] struct {
// Has unexported fields.
}
func (t *Template[T]) Meta() TemplateMeta
func (t *Template[T]) Name() string
func (t *Template[T]) Render(r *Renderer, to Recipient, v T) (*Message, error)
| Identifier | Does |
|---|---|
Compile | Compiles the template src called name against its data type T and the kit k. It checks everything that doesn't depend on data or on the renderer: the Comark source, the frontmatter (core keys and the kit's), every component against its kit schema, every merge tag and binding against T and Recipient, and a literal from. It returns the template or every error joined, each an *ir.Error with name:line:col. T is a struct, or map[string]any for untyped data, whose paths are read at render time. A binding needs its exact registered type, so untyped data can't satisfy one. |
MustCompile | Compile that panics on error, for package-level template variables compiled at init. |
Template[T] | A compiled template whose data is a T. Immutable and safe for concurrent use. |
Template.Render | Renders for recipient to with data v, and checks everything that depends on data or on the renderer: the same kit, a known profile, a value for every merge tag without a fallback, every URL, the subject, the addresses, from against the profile, the unsubscribe URL of a ListUnsubscribe profile, and the HTML size (an error at 100 KB, a warning over 90 KB). It returns the message or an error, never both. |
Template.Meta | A copy of the template's description. |
Template.Name | The template name. |
type TemplateMeta struct {
Name string
Profile string // frontmatter `profile:`
Tags []TagInfo // in source order
Components []string // top-level component names in order, e.g. "hero"
Warnings []string // "name:line:col: warning: msg"
}
type TagInfo struct {
Path string // dotted path, e.g. "driver.first_name"
Type string // the Go type it resolves to, e.g. "string", "shop.Receipt"
Pos string // "line:col" in the template source
Binding bool // a :key="path" binding rather than a {{path}} tag
}
TemplateMeta describes a compiled template: the profile it names, the tags and components it uses, and its compile warnings. TagInfo is one merge tag or binding, and is what lttr tags prints. See Compile errors and Merge tags and data.
Pass trusted HTML
type TrustedHTML struct {
HTML template.HTML
Text string
}
TrustedHTML is HTML the application vouches for, passed into a component attribute of type html. lttr does not sanitise it: the HTML is inserted verbatim into the component's html.tmpl, so never build it from user input without sanitising it first. Text is the plain-text alternative used in the text part, and is required when HTML is non-empty. A template gives it as the attribute's one merge tag, with no fallback and nothing around it (::panel{body="{{summary}}"}), and the path must name a field of exactly this type, not a pointer, in typed data. The lint package checks the rendered email for markup email clients mishandle; it is not a sanitiser, and doesn't catch event handlers or javascript: URLs. See Pass trusted HTML.
Describe samples
type Sample struct {
// Has unexported fields.
}
func NewSample[T any](file string, src []byte, data T, to Recipient) Sample
func (s Sample) Compile(k *kit.Kit) error
func (s Sample) Data() any
func (s Sample) File() string
func (s Sample) Name() string
func (s Sample) Render(r *Renderer) (*Message, error)
func (s Sample) Source() []byte
func (s Sample) WithData(js []byte) (Sample, error)
func (s Sample) WithSource(src []byte) Sample
type SampleSet struct {
Kit *kit.Kit
Config Config
Samples []Sample
}
func KitSamples(k *kit.Kit, cfg Config) (*SampleSet, error)
| Identifier | Does |
|---|---|
Sample | One template source with the data it is rendered with. An opaque value, safe to copy and for concurrent use: copies share its compiled template, compiled once per kit. |
NewSample | Makes a sample of src, read from file, rendered for to with data. T may be a struct or map[string]any, as for Compile. It keeps its own copy of src but keeps data itself, so don't modify data reachable through it afterwards. |
Sample.Name, File, Source, Data | The template's name from its frontmatter's template: key (read without compiling, "" when missing), the file name, a copy of the source, and the data. |
Sample.WithData | A copy whose data is a JSON value decoded into a fresh value of the sample's data type, strictly for structs. An error is an *ir.Error at the line and byte column in the JSON (line:col: data: msg). |
Sample.WithSource | A copy with new template source, such as an unsaved editor buffer. |
Sample.Compile | Compiles against k and returns Compile's errors. A template without a template: key is compiled under its file name without .md. |
Sample.Render | Renders with r for the sample's recipient and data, compiling first against r's kit when needed. |
SampleSet | A kit, the config to render it with, and its samples: what lint.Check, lint.Golden, lttr kit check and previews take. |
KitSamples | Builds the set of a kit's samples/*.md, in file name order, with each one's samples/samples.yaml entry as untyped data, rendered for reader@example.com. Problems with samples/ are returned, joined, with the set. |
See Goldens and testing.
Configure a renderer
func NewRenderer(cfg Config) (*Renderer, error)
type Renderer struct {
// Has unexported fields.
}
func (r *Renderer) Kit() *kit.Kit
func (r *Renderer) Profile(name string) (Profile, bool)
func (r *Renderer) Profiles() []Profile
type Config struct {
// Kit supplies the templates, components and tokens messages render
// with. Templates must be compiled against the same kit.
Kit *kit.Kit
// Profiles are the sender profiles templates may name; names are
// unique.
Profiles []Profile
// AssetBase is the base URL of the kit's assets (logos and the like),
// available to templates as {{var "asset_base"}}. It must be an
// absolute https URL, or a relative URL when AllowRelativeURLs is set.
// Empty keeps the kit's own asset_base default, which must then pass
// the same rule; when the kit has no default either, asset_base is
// empty (fine for a kit that has no assets).
AssetBase string
// Vars override the kit's var defaults; every key must be a kit var
// other than asset_base, which AssetBase sets.
Vars map[string]string
// AllowRelativeURLs lets relative URLs through the URL checks and
// AssetBase. It is for previews only: mail clients cannot resolve them.
AllowRelativeURLs bool
}
| Identifier | Does |
|---|---|
NewRenderer | Validates cfg and prepares the kit for rendering. It reports every problem at once: a nil kit, missing, unnamed or duplicate profiles, a bad From or FromDomain, a From off its domain, a header SetHeader would refuse, an asset base that isn't https (or relative with AllowRelativeURLs), an unknown var or a var value with <, > or a control character, and the kit's own styles.css errors. It keeps its own copy of the profiles. |
Renderer | Renders compiled templates for one Config. Immutable and safe for concurrent use. |
Renderer.Kit | The kit it renders with. |
Renderer.Profile | A copy of the named profile. |
Renderer.Profiles | Copies of every profile, in Config order. |
Config | Everything a Renderer needs from the application. |
type Profile struct {
// Name is what frontmatter `profile:` refers to.
Name string
// From is the fixed sender. When it is zero the template must set
// frontmatter `from`; when it is set, the template must not.
From mail.Address
// FromDomain, when set, is the domain a frontmatter `from` (and From)
// must be on, compared case-insensitively.
FromDomain string
// Headers are added to every message of the profile, for example
// X-SES-CONFIGURATION-SET. They follow the Message.SetHeader rules.
Headers map[string]string
// ListUnsubscribe sets the RFC 8058 one-click unsubscribe headers from
// Recipient.UnsubscribeURL, which must then be an absolute https URL.
ListUnsubscribe bool
}
type Recipient = data.Recipient
Profile is a sender profile: who a message is from and which headers it carries. A template names it in frontmatter, and Render copies the name to Message.Profile so the application can route on it. It holds no sending policy. Recipient is the addressee: Address, Name and UnsubscribeURL (see data). Merge tags the data type doesn't define resolve against it. See Profiles and config.
Work with a message
type Message struct {
// Template and Profile name the template and the sender profile that
// produced the message, so an application can route on them. They are
// not written to the wire.
Template, Profile string
// From and To are the sender and the single recipient.
From, To mail.Address
// Subject is the Subject header; Preheader is the hidden inbox preview
// text already embedded in HTML.
Subject, Preheader string
// HTML and Text are the two bodies of the multipart/alternative message.
HTML, Text string
// Warnings are non-fatal findings from compile and render.
Warnings []string
// Has unexported fields.
}
func (m *Message) Clone() *Message
func (m *Message) Header(name string) string
func (m *Message) Headers() []string
func (m *Message) MIME(date time.Time) ([]byte, error)
func (m *Message) SetHeader(name, value string) error
func (m *Message) SetListUnsubscribe(u string) error
| Identifier | Does |
|---|---|
Message | A rendered email: the envelope, both bodies and any extra headers. |
Message.Clone | A deep copy. Changing the copy's headers or warnings doesn't affect the original. |
Message.Header | The value of a custom header, or "". The name is matched case-insensitively. |
Message.Headers | The canonical names of the custom headers, sorted, which is the order MIME writes them in. |
Message.MIME | Serialises the message as RFC 5322 multipart/alternative with CRLF line endings: text first, then HTML, both UTF-8 and quoted-printable. Non-ASCII subjects and names are RFC 2047 encoded. The Message-ID and boundary come from crypto/rand, so two calls give different bytes. |
Message.SetHeader | Sets a custom header. The name must be printable ASCII without : and not one MIME writes itself, and List-Unsubscribe is reserved for SetListUnsubscribe. The value must be printable ASCII with no CR, LF or NUL, which is what stops header injection. |
Message.SetListUnsubscribe | Sets the RFC 8058 one-click headers, List-Unsubscribe: <u> and List-Unsubscribe-Post: List-Unsubscribe=One-Click. u must be an absolute https URL. |
See Message and MIME.
Send
type Sender interface {
// Send delivers m or returns why it could not.
Send(ctx context.Context, m *Message) error
}
type SMTP struct {
// Addr is the server's host:port.
Addr string
// Auth authenticates the session. When set, the server must advertise
// AUTH; nil sends without authentication.
Auth smtp.Auth
// Headers are added to every message sent, for example
// X-SES-CONFIGURATION-SET. They pass the same checks as
// Message.SetHeader and are applied to a copy of the message.
Headers map[string]string
// Now stamps the Date header; nil means time.Now.
Now func() time.Time
}
func (s *SMTP) Send(ctx context.Context, m *Message) error
func (s *SMTP) SendWithID(ctx context.Context, m *Message) (messageID string, err error)
Sender delivers a message. Routing (which Sender a message goes through, for example by Message.Profile) and suppression are the application's job. SMTP.Send serialises a copy of m with s.Headers added and delivers it over one session: MAIL FROM is m.From.Address and RCPT TO is m.To.Address. It uses STARTTLS when the server offers it, verified against the host of Addr, and checks the message before connecting. Cancelling ctx aborts the dial and the session. SMTP.SendWithID is Send, returning the Message-ID header it set, angle brackets included (<9f…@example.com>), so a caller can log or show which message went out. On an error it returns "". See SMTP.
Version
const Version = "v0.2.0"
The release this source tree is, as recorded in CHANGELOG.md. It is maintained by hand. The Git tag the release workflow cuts is the authoritative version of a published module. See Releasing.
Import lttr/kit
import "github.com/sulv-io/lttr/kit"
Load a kit and read its schema. The view types are what kit templates execute with. See What is a kit.
Load a kit
func Load(fsys fs.FS, opts ...Option) (*Kit, error)
type Option func(*options)
func Funcs(fm map[string]any) Option
func Types(defs ...TypeDef) Option
type TypeDef struct {
Name string
Type reflect.Type
}
func TypeOf[T any](name string) TypeDef
const VarAssetBase = "asset_base"
| Identifier | Does |
|---|---|
Load | Loads the kit rooted at fsys: decodes kit.yaml and every components/*/component.yaml, parses every template, checks every cross-reference and statically checks every template against its view. It returns the kit or every problem, joined, each with its kit-relative file position. |
Option | Configures Load. |
Types | Registers the Go types the kit's types list names. |
TypeDef, TypeOf | A Go type registered under a name. kit.TypeOf[Invoice]("Invoice") registers Invoice as Invoice. |
Funcs | Registers extra typed template functions for every kit template. Names must not collide with the core functions or the text/template builtins. The renderer installs the same functions. |
VarAssetBase | The var every kit has: the renderer's asset base URL, {{var "asset_base"}}. |
See Go types and funcs.
type Kit struct {
// Has unexported fields.
}
func (k *Kit) Assets() fs.FS
func (k *Kit) BlocksHTML() *htmltemplate.Template
func (k *Kit) BlocksText() *texttemplate.Template
func (k *Kit) Component(name string) (*Component, bool)
func (k *Kit) Components() []*Component
func (k *Kit) Dark() bool
func (k *Kit) Default() string
func (k *Kit) ExtraFuncs() map[string]any
func (k *Kit) Frontmatter() map[string]AttrSpec
func (k *Kit) Inline() InlineStyles
func (k *Kit) LayoutHTML() *htmltemplate.Template
func (k *Kit) LayoutText() *texttemplate.Template
func (k *Kit) Limit(inline string) (int, bool)
func (k *Kit) Name() string
func (k *Kit) Samples() fs.FS
func (k *Kit) Span(class string) (Span, bool)
func (k *Kit) Spans() []string
func (k *Kit) Styles() *texttemplate.Template
func (k *Kit) Token(name string) (Token, bool)
func (k *Kit) Var(name string) (string, bool)
func (k *Kit) Vars() []string
func (k *Kit) Version() int
A loaded kit, immutable. The values its accessors return must not be modified.
| Method | Returns |
|---|---|
Assets, Samples | The assets/ and samples/ directories, empty when the kit has none. |
BlocksHTML | The parsed blocks.html: paragraph, heading, list, actions, action, table and inline, image when a component allows images, and optionally quote. |
BlocksText | The text forms of the blocks: the core defaults, overridden define by define by the kit's blocks.txt. |
Component | The component with the given name or alias, case-insensitively. |
Components | Every component, sorted by name. |
Dark | Whether the kit supports dark mode (dark: true). |
Default | The component loose Markdown goes into, or "" when loose Markdown is a compile error. |
ExtraFuncs | The kit's extra template functions. |
Frontmatter | The kit's frontmatter keys by name. |
Inline | The inline styles built from kit.yaml inline. |
LayoutHTML, LayoutText | The parsed layouts. Clone before adding functions or executing. |
Limit | The template-wide limit for an inline component such as button. |
Name, Version | kit.yaml name and version (0 when absent). |
Span, Spans | The style of a [text]{.class} span class, and every span class name, sorted. |
Styles | The parsed styles.css, a text/template executed with a nil dot. |
Token | The design token with the given name. |
Var, Vars | A var's default, and every var name, sorted, asset_base included. |
type Error struct {
Path string
Line, Col int
Msg string // ends with " (did you mean X?)" when Suggestion is set
// Suggestion is the known name nearest to the unknown one Msg quotes
// (a schema key, a token or var name): the text that replaces that
// quoted name, for quick fixes; empty when none. Line and Col are where
// the error is reported, which is not necessarily where the name is
// written.
Suggestion string
}
func (e *Error) Error() string
One kit problem at a position in a kit file, rendered as path:line:col: msg, such as components/footer/html.tmpl:4:188: var: unknown var "compnay" (did you mean company?). Path is relative to the kit root ("" for a problem with the Load options). Line and Col are 1-based, and Col counts bytes. Line 0 means no position and Col -1 an unknown column, which Error leaves out. See Template checking.
Read the schema
type Component struct {
Name string // canonical name, the directory name
Class string // optional label spacing selectors match as ".class"
Dir string // kit-relative directory, e.g. "components/receipt"
Aliases []string // lower-case alternative names
Attrs map[string]AttrSpec
Bindings map[string]BindSpec
Content ContentSpec
Children *ChildSpec // nil: no nested components
MustFollow []string // component names this one must directly follow (any of)
Limits map[string]int // caps on :button / :link inside this component's content (yaml `limits`)
Spacing Spacing
HTML *htmltemplate.Template // html.tmpl with blocks.html; clone before executing
Text *texttemplate.Template // text.tmpl with the text blocks; nil: no text form
}
type AttrSpec struct {
Name string
Type AttrType
Required bool
RequiredWith string // required when this other attribute is set
Default string // literal default, valid for Type
Values []string // allowed values of an enum
}
type AttrType string
const (
AttrText AttrType = "text" // merge tags allowed; string
AttrURL AttrType = "url" // evaluated and checked; template.URL
AttrInt AttrType = "int" // int
AttrFlag AttrType = "flag" // bool
AttrEnum AttrType = "enum" // one of Values; string
AttrList AttrType = "list" // comma-separated literal; []string
AttrInline AttrType = "inline" // one paragraph of Markdown; Inline
// AttrHTML is HTML the application passes from Go: one {{path}} to an
// lttr.TrustedHTML field of typed data. It is template.HTML in
// html.tmpl and the plain-text alternative, a string, in text.tmpl.
// Kit frontmatter keys cannot have it.
AttrHTML AttrType = "html"
)
func (t AttrType) TextValueType() reflect.Type
func (t AttrType) ValueType() reflect.Type
type BindSpec struct {
Name string
TypeName string // the name in kit.yaml `types`
Type reflect.Type // the registered type
Required bool
}
type ChildSpec struct {
Component string
Min, Max int
}
Component is one kit component: its schema from component.yaml and its parsed templates. AttrSpec declares an attribute or a kit frontmatter key. AttrType.ValueType is the Go type an HTML view holds for it, and AttrType.TextValueType the type a text view holds, which differs only for html (a string, the plain-text alternative). BindSpec declares a binding of a registered type. ChildSpec says which component nests inside this one and how many times (a zero Max means no limit). See Component schemas.
type ContentSpec struct {
None bool // no content at all
Allow []BlockKind
Inline []InlineKind
Headings []int
MinParagraphs, MaxParagraphs int
Min, Max int // block counts
MaxColumns int // table columns
TableHeader bool
// MaxKind caps the top-level blocks of a kind (yaml `max_kind:
// {heading: 1}`); a kind absent from it has no cap. Every kind in it is
// in Allow.
MaxKind map[BlockKind]int
// Sequence, when set, is the exact kinds of the top-level blocks, in
// order (yaml `sequence: [heading, paragraph]`). Every kind in it is in
// Allow.
Sequence []BlockKind
}
func (c ContentSpec) Allows(b BlockKind) bool
func (c ContentSpec) AllowsInline(i InlineKind) bool
type BlockKind string
const (
BlockParagraph BlockKind = "paragraph"
BlockHeading BlockKind = "heading"
BlockList BlockKind = "list"
BlockActions BlockKind = "actions"
BlockTable BlockKind = "table"
BlockImage BlockKind = "image" // opt-in (ruling K7)
// BlockInline is the Kind of the view the `inline` define executes
// with; it is not a content block and cannot be allowed.
BlockInline BlockKind = "inline"
)
type InlineKind string
const (
InlineStrike InlineKind = "strike"
InlineLinkTitle InlineKind = "link_title"
)
ContentSpec says what Markdown a component takes. A zero count means no limit, and empty Headings allows every level. Allows and AllowsInline report whether a block kind or an opt-in inline feature is allowed.
type Spacing struct {
Top, Bottom int
First, Last *Edge
After map[string]Edge
}
type Edge struct {
Top, Bottom, PrevBottom *int
}
A component's section padding. After is keyed by a component name or .class and applies when this component directly follows it. An Edge overrides spacing in one position, nil fields keep the default, and PrevBottom adjusts the previous component's bottom.
type Token struct {
Name, Value, Light, Dark string
}
func (t Token) Base() string
type Span struct {
Color, Font, Weight string
Size int
}
type InlineStyles struct {
Link, Code, Strong, Em, Strike string
}
A Token is a design token from kit.yaml. A colour written {light: …, dark: …} sets Light and Dark, any other token sets Value, and Base is the value outside dark mode. A Span is a span class's style: Color, Font and Weight hold a token name or a CSS literal, and Size is in px. InlineStyles are the style strings for Markdown inlines, with token names replaced by their values. See kit.yaml.
Read the views
The data every kit template executes with. See Templates and views.
type View struct {
Name string // canonical component name
Attrs Attrs // evaluated attributes
Bind Bind // bound Go values
Content Content // compiled Markdown content; render with {{content .Content}}
Children []ChildView // nested components, in order
Section Section // resolved spacing and position
Doc Doc // document-wide values
}
type Attrs map[string]any
type Bind map[string]any
type Content interface{ KitContent() }
type Inline interface{ KitInline() }
type ChildView struct {
Name string
Attrs ChildAttrs
Bind ChildBind
Content Content
Children []ChildView // the child's own nested components, in order
Section Section // resolved spacing and position among its siblings
Doc Doc
// Has unexported fields.
}
type ChildAttrs map[string]any
type ChildBind map[string]any
type Section struct {
Top, Bottom int // padding in px, resolved from the schema's spacing
Index int // 0-based position among its siblings
First, Last bool // the first or last of its siblings
Prev, Next string // neighbouring sibling component names ("" at the ends)
}
| Identifier | Is |
|---|---|
View | What a component's html.tmpl and text.tmpl execute with. |
Attrs, ChildAttrs | Evaluated attribute values by name, typed by the schema: text and enum a string, url a template.URL, int an int, flag a bool, list a []string, inline an Inline, and html a template.HTML in html.tmpl and a string in text.tmpl. |
Bind, ChildBind | Bound Go values by binding name, each of its registered type. An optional binding the template didn't give is nil. |
Content | Compiled Markdown content. The core content function renders it through the kit's blocks. |
Inline | A compiled one-paragraph Markdown value, rendered by the core inline function. |
ChildView | One nested component, at any depth, with its own Children. A parent reads its direct children's fields inline, and runs a child's own template with the core render function. |
Section | A component's resolved spacing and position among its siblings: the document's components at the top level, its parent's other children when nested. |
type Doc struct {
Subject, Preheader string
Profile Profile
Recipient Recipient
Front Front
}
type Front map[string]any
type Profile struct {
Name string // profile name, e.g. "transactional"
From string // formatted From address
}
type Recipient struct {
Address, Name string
UnsubscribeURL template.URL // checked; empty when unset
}
type LayoutView struct {
Subject, Preheader string
Styles template.CSS // executed styles.css
Body template.HTML // the components' HTML, in order
Doc Doc
}
type TextLayoutView struct {
Subject, Preheader string
Body string // the components' text forms, in order
Doc Doc
}
Doc holds the document-wide values every template can read: .Doc.Profile.Name, .Doc.Recipient.UnsubscribeURL, and the kit's frontmatter keys in .Doc.Front, typed like attributes. LayoutView and TextLayoutView are what layout.html and layout.txt execute with.
type BlockView struct {
Kind BlockKind
Variant string // the variant passed to content or inline ("" for none)
Index int // 0-based position among the content's top-level blocks
First bool // the first top-level block
Last bool // the last top-level block
Prev BlockKind // the previous top-level block's kind ("" for the first)
Level int // heading level 1–6
Ordered bool // an ordered list
Number int // a list item's 1-based number
HTML template.HTML // rendered inline HTML (paragraph, heading, list item, inline)
Text string // plain text, soft breaks as spaces; for a table, the core table layout (dot leaders for two columns, padded columns otherwise)
Lines string // plain text with soft breaks kept as "\n"
Inline []InlineView // the inline nodes of a paragraph, heading, list item or inline value
Items []BlockView // list items
Actions []ActionView // action row items
Rows [][]CellView // table body rows
Header []CellView // table header row (empty when the table has none)
Align []string // table column alignment: "", "left", "center" or "right"
Src template.URL // image source, checked
Alt string // image alt text
Title string // image title
}
type CellView struct {
HTML template.HTML
Text string
Lines string // plain text with soft breaks kept as "\n"
Inline []InlineView // the cell's inline nodes
Strong bool // the whole cell is strong
}
type ActionView struct {
Label string
Href template.URL
Primary bool // a :button
Arrow bool // a :link that asks for a trailing arrow
}
type InlineView struct {
Kind string
Text string // text and code: the evaluated text
Href template.URL // link: the target, already checked
Title string // link: the title (when the content allows link titles)
Classes []string // span: its classes
Hard bool // break: a hard break (soft otherwise)
Children []InlineView // strong, em, strike, link and span: the content
}
type Leader struct {
Label, Value, Sub string
}
BlockView is what every blocks.html and blocks.txt define executes with, except action, which gets an ActionView. CellView is one table cell. InlineView is one inline node (text, code, strong, em, strike, link, span or break) for kits that render inline content themselves. Leader is one dot-leader row for the text function leaders.
List the core functions
func CoreFuncNames() []string
func HTMLFuncs() map[string]any
func TextFuncs() map[string]any
CoreFuncNames returns the name of every core template function, sorted; kit.Funcs names must avoid them. HTMLFuncs and TextFuncs return stubs with the exact signatures of the core functions available to HTML templates (layout.html, blocks.html, html.tmpl) and to text templates. The renderer installs real functions under the same names and types. Templates and views documents each function.
Import lttr/render
import "github.com/sulv-io/lttr/render"
The engine that executes a kit's templates. Template.Render uses it, so an application meets it through its error types:
type ComponentError struct {
Name string // the Markdown template's name
Pos ir.Pos // the component's position in it
Component string // the component's canonical name
Err error
}
func (e *ComponentError) Error() string
func (e *ComponentError) Unwrap() error
type TemplateError struct {
Path string
Line, Col int
Msg string
// Fail marks an error raised by the core `fail` function: Msg is then
// the kit's message, reported without the kit position when the
// template is a component's (ruling R7).
Fail bool
}
func (e *TemplateError) Error() string
| Identifier | Is |
|---|---|
ComponentError | An error executing a component's template, reported at the component's position in the Markdown template: name:line:col: component: msg. Unwrap returns the *TemplateError. |
TemplateError | A runtime error in a kit template (a nil pointer, a missing map key, a function error or a fail) at a position in a kit file, rendered as path:line:col: msg. Line is 0 when the position is unknown, and Col 0 when only the line is known. A kit template error is always returned as an error, never a panic. |
The package also exports Engine, New, Options, Input and IsUnsafeVarRune, for tools that render a compiled ir.Document without the root package. go doc github.com/sulv-io/lttr/render lists them.
Import lttr/ir
import "github.com/sulv-io/lttr/ir"
The compiler from parsed Comark to the component IR. Compile and Render report template errors with its error type:
type Error struct {
Name string // template (or copy) name
Pos Pos
Msg string // ends with " (did you mean X?)" when Suggestion is set
// Suggestion is the known name nearest to the unknown one Msg quotes,
// for quick fixes: the text that replaces that name (".muted",
// ":order"; for a merge tag or binding, the whole path, such as
// "driver.rating" for {{drivr.rating}}); empty when none. Pos is where
// the error is reported, which is not necessarily where the name is
// written.
Suggestion string
}
func (e *Error) Error() string
type Pos = comark.Pos
Error is a compile or render error at a position in a template, rendered as name:line:col: msg. Suggestion is set for an unknown name close to a known one, such as a misspelt merge tag, component, attribute or span class, and the message then ends with (did you mean X?). The warning type, Diagnostic, carries the same field. kit.Error has one too, for token, var and schema-key names in kit templates. Pos is a 1-based line and byte column, and prints as line:col. The rest of the package, the IR types and ir.Compile, is for tools.
Tell errors apart
errors.As finds each type in a joined or wrapped error:
package main
import (
"errors"
"fmt"
"net/mail"
"github.com/sulv-io/lttr"
"github.com/sulv-io/lttr/ir"
"github.com/sulv-io/lttr/kits/quiet"
"github.com/sulv-io/lttr/render"
)
func main() {
k := quiet.MustKit()
// Compile joins every template error; each is an *ir.Error.
_, err := lttr.Compile[struct{}](k, "broken", []byte("---\ntemplate: broken\nprofile: buyer\nsubject: Hi\n---\n\n::statment\n# Hi\n::\n"))
var ie *ir.Error
if errors.As(err, &ie) {
fmt.Printf("compile: %s at %s: %s\n", ie.Name, ie.Pos, ie.Msg)
}
// Render reports a kit template's failure as a *render.ComponentError
// at the component, wrapping the *render.TemplateError in the kit file.
t := lttr.MustCompile[struct{}](k, "map", []byte("---\ntemplate: map\nprofile: buyer\nsubject: Hi\n---\n\n::map\n::\n"))
r, err := lttr.NewRenderer(lttr.Config{
Kit: k,
Profiles: []lttr.Profile{{Name: "buyer", From: mail.Address{Address: "orders@loam.example"}}},
AssetBase: "https://loam.example/assets/email",
})
if err != nil {
panic(err)
}
_, err = t.Render(r, lttr.Recipient{Address: "ada@example.com"}, struct{}{})
var ce *render.ComponentError
var te *render.TemplateError
if errors.As(err, &ce) && errors.As(err, &te) {
fmt.Printf("render: %s at %s in %s\n", ce.Component, ce.Pos, ce.Name)
fmt.Printf(" kit: %s:%d:%d, fail: %t: %s\n", te.Path, te.Line, te.Col, te.Fail, te.Msg)
}
}
compile: broken at 7:1: unknown component "statment" (did you mean statement?)
render: map at 7:1 in map
kit: components/map/html.tmpl:5:131, fail: true: alt or pickup and dropoff are required
Import lttr/lint
import "github.com/sulv-io/lttr/lint"
Checks rendered email for email safety, and runs sample sets through the checks and golden files. lttr lint and lttr kit check use it. See Goldens and testing and Email-safe HTML.
func Lint(doc string, opts Options) []string
type Options struct {
// Dark requires <meta name="color-scheme" content="light dark">. Set it
// for documents from a dark-capable kit.
Dark bool
}
func Check(set *lttr.SampleSet) []Problem
func Failures(problems []Problem) []Problem
type Problem struct {
Sample string // the sample's template name; "" for a problem with the whole set
File string // the sample's file, e.g. "01-box-on-its-way.md"
Line, Col int // 1-based position in File; 0 when unknown
Msg string // ends with " (did you mean X?)" when Suggestion is set
// Warning marks a compile warning, such as a malformed merge tag or a
// missing preheader. It is reported, but does not make the sample fail.
Warning bool
// Suggestion is the known name nearest to the unknown one Msg quotes,
// the text that replaces it (see ir.Error.Suggestion), for quick
// fixes; empty when none.
Suggestion string
// Err is the compile or render error the problem reports (one of a
// joined error), or the sample set's config error, for errors.As: an
// *ir.Error, a *render.ComponentError wrapping the kit template's
// *render.TemplateError, and so on. It is nil for lint messages,
// template name problems and warnings. String does not use it.
Err error
}
func (p Problem) String() string
func Golden(t testing.TB, set *lttr.SampleSet, dir string, update bool)
| Identifier | Does |
|---|---|
Lint | Runs the email-safety lint over one rendered HTML document and returns one message per violation, most with a byte offset. An empty result means clean. Safe for concurrent use. |
Options | The optional rules: Dark requires the color-scheme meta. |
Check | Compiles every sample of set, renders it with set.Config and lints its HTML with Options{Dark: set.Kit.Dark()}. It returns every problem, in sample order after any problem with the template names (two samples with one name, or a name that isn't safe as a file name). A sample's compile warnings come first among its problems, then its errors. Compile errors and warnings carry their position in the sample's file, and lint messages start with html: . Problems with Warning set do not make a sample fail. set.Config.Kit may be nil, meaning set.Kit. |
Failures | The problems without Warning set, in order: the ones a test reports with t.Error. |
Problem, Problem.String | One thing Check found: an error, or a compile warning with Warning set. String prints file:line:col: msg, or file:line:col: warning: msg for a warning, with an unknown column or position left out. Suggestion carries the "did you mean" name of the error or warning, for quick fixes, and Err the underlying compile or render error for errors.As (nil for lint messages, name problems and warnings). |
Golden | From a test: compares each sample's render with <dir>/<Name>.html and .txt byte for byte, in a subtest per sample, and reports a line diff (the first 20 differing lines) or a missing file. With update it writes the files instead. A set with no samples, or a duplicate or unsafe name, fails before anything is rendered or written, and a sample that fails to compile or render fails with that error and writes nothing. Compile warnings don't fail it. |
Import lttr/data
import "github.com/sulv-io/lttr/data"
Resolves the dotted paths of merge tags and bindings against a template's data type, and defines Recipient. Kit-specific types such as money and receipts live with the kits that bind them.
Recipient
type Recipient struct {
Address string `json:"address"` // RFC 5322 address, e.g. "ann@example.org" or "Ann <ann@example.org>"
Name string `json:"name"` // display name for the To header
UnsubscribeURL string `json:"unsubscribe_url"` // one-click unsubscribe URL; empty when unset
}
The person an email is addressed to, and always the second root paths resolve against, after the template's data type. {{name}} is Name unless the data type has its own name. The root package's lttr.Recipient is this type.
Scalars
func IsScalar(t reflect.Type) bool
func FormatScalar(v reflect.Value) string
func FormatValue(v reflect.Value) (s string, ok bool)
| Identifier | Does |
|---|---|
IsScalar | Whether a type may be a merge tag's value: a type implementing fmt.Stringer with a value receiver, a string kind or any integer kind. Floats, bools, structs other than Stringers, slices and maps aren't. |
FormatScalar | Renders a scalar as text: a Stringer's String(), a string's value, or an integer in decimal. |
FormatValue | Formats a value read from untyped data: a scalar as FormatScalar does, plus the float and bool kinds JSON and YAML decode to (12.5). ok is false for a map, a list or a struct that isn't a Stringer. |
Path resolution
type Scope struct {
// Has unexported fields.
}
func NewScope(roots ...Root) Scope
func (s Scope) Resolve(path string) (Accessor, error)
type Root struct {
Slot int
Type reflect.Type
}
type Accessor struct {
// Has unexported fields.
}
func (a Accessor) DeclaredType() reflect.Type
func (a Accessor) Dynamic() bool
func (a Accessor) Get(roots []reflect.Value) (reflect.Value, bool)
func (a Accessor) Path() string
func (a Accessor) Type() reflect.Type
| Identifier | Does |
|---|---|
NewScope, Scope | An ordered, immutable set of roots. The first segment of a path is looked up in each root in turn, and the first match wins. |
Scope.Resolve | Compiles a dotted path into an Accessor, once, at compile time. It follows struct fields by JSON name (with promotion through embedded fields and pointers) and map keys. A map[string]any root is untyped: any first segment resolves into it, and the rest is read at render time. |
Root | One root: the slot of its value in the slice passed to Get, and its type. |
Accessor | A precompiled path, a plain value that can be copied freely. |
Accessor.Get | Walks the precomputed steps against the roots. It returns false on a nil pointer, a missing map key or untyped data it can't descend into. It never parses the path. |
Accessor.Dynamic | Whether the path runs through untyped data, whose type is only known at render time. |
Accessor.Path, Accessor.Type | The dotted path, and the type it resolves to with pointers dereferenced. |
Accessor.DeclaredType | The type the path resolves to as declared, pointers kept (*T where Type returns T). |
See Merge tags and data.
Import lttr/kits/quiet
import "github.com/sulv-io/lttr/kits/quiet"
The Quiet kit: the kit files, the Go types its components bind and its extra template functions. See The Quiet kit.
Load the kit
func Files() fs.FS
func Kit() (*kit.Kit, error)
func MustKit() *kit.Kit
| Identifier | Does |
|---|---|
Files | The kit's files, for tools that inspect or copy a kit. |
Kit | The loaded kit. It loads on the first call, and later calls return the same *kit.Kit, so templates compiled against Kit() render with any Renderer whose Config uses it. |
MustKit | Kit for program initialisation. It panics if the kit doesn't load, which only a broken build can cause. |
Money
type Money struct {
Minor int64
Currency Currency
Symbol string
}
func USD(minor int64) Money
func (m Money) Approx() string
func (m Money) String() string
type Exact Money
func (e Exact) String() string
type Currency string
const (
USDCode Currency = "USD"
EURCode Currency = "EUR"
GBPCode Currency = "GBP"
)
| Identifier | Does |
|---|---|
Money | An amount in minor units (cents). Symbol, when set, is the display prefix ($, A$). Otherwise a known currency's prefix is used, and any other code is written before the amount (ABC 1.50). |
USD | A Money in US dollars from a minor-unit amount. |
Money.String | The prefix, comma thousands separators, no decimals for whole amounts, and a U+2212 minus before the prefix: $1,019.90, −$65.10, $256. |
Money.Approx | Rounded half away from zero to whole units, with ≈ : ≈ US$13. |
Exact, Exact.String | A Money that always shows two decimals ($1,085.00), for breakdowns that must line up. |
Currency, USDCode, EURCode, GBPCode | ISO 4217-style codes. Every known currency has two minor digits. |
Bound types
type Receipt struct {
Lines []ReceiptLine
Fees []Fee
Total Money
TotalUSD *Money // optional; shown under the total as "≈ US$…"
TotalLabel string // "" = the receipt component's total_label
}
type ReceiptLine struct {
Name, Detail string
Qty int
Amount Money
Thumb string // thumbnail URL; "" shows the Tone ground
Tone Tone
}
type Fee struct {
Label string
Amount Money
}
type StockItem struct {
Name, SKU string
Left int
}
type Product struct {
Name string
Price Money
Href, Image string
Tone Tone
}
type Tone string
const (
ToneNone Tone = ""
ToneWarm Tone = "warm"
ToneSea Tone = "sea"
ToneSun Tone = "sun"
ToneMap Tone = "map"
)
func (t Tone) Valid() bool
| Identifier | Is |
|---|---|
Receipt | An order summary for ::receipt{:order="…"}: line items, fees and a total. |
ReceiptLine | One line item, with an optional thumbnail. |
Fee | A labelled charge on a receipt, such as delivery or tax. |
StockItem | The stock left of one product. ::stock{:items="…"} binds a []StockItem. |
Product | A product tile. ::products{:items="…"} binds a []Product. |
Tone, Tone.Valid | The placeholder ground shown where a tile, band or thumbnail has no image. ToneNone is the neutral ground. |
The kit registers these types under the names Money, Exact, Receipt, ReceiptLine, Fee, StockItem, Product and Tone, and the bound lists as StockItems ([]StockItem), Products ([]Product) and Strings ([]string).
Import lttr/kits/plain
import "github.com/sulv-io/lttr/kits/plain"
The minimal starter kit: one left-aligned column, a system sans-serif stack, square buttons and light and dark colours, with the components section (the default), button, image, columns (of column) and footer. It registers no Go types or template functions, and lttr kit init copies its files.
func Files() fs.FS
func Kit() (*kit.Kit, error)
func MustKit() *kit.Kit
func Set(cfg lttr.Config) (*lttr.SampleSet, error)
| Identifier | Does |
|---|---|
Files | The kit's files: kit.yaml, the layouts, styles, blocks, components, assets and samples. |
Kit | The loaded kit, the same *kit.Kit on every call. Safe for concurrent use. |
MustKit | Kit that panics on error. The embedded kit is tested, so an error means a broken build. |
Set | The kit's samples (samples/*.md with their samples.yaml data, untyped) as a sample set rendered with cfg, as lttr.KitSamples builds it. cfg.Kit may be nil or MustKit(), and cfg.Profiles must name the samples' profile, default. |
See What is a kit and Build your own kit.