Merge tags and data
A template is compiled against one data type, its T. With a struct, every {{path}} merge tag and every :key="path" binding is resolved against that type when you call lttr.Compile, so a typo is a compile error with a line and column, not a blank in a sent email. Rendering then follows precompiled accessors and never parses a path.
package main
import (
"fmt"
"log"
"net/mail"
"github.com/sulv-io/lttr"
"github.com/sulv-io/lttr/kits/plain"
)
// Cents prints as dollars: a fmt.Stringer is a scalar.
type Cents int64
func (c Cents) String() string { return fmt.Sprintf("$%d.%02d", c/100, c%100) }
type Courier struct {
FirstName string `json:"first_name"`
Phone string // no json tag: matched as "phone"
}
type Links struct {
TrackURL string `json:"track_url"`
}
type OrderShipped struct {
Links // embedded: {{track_url}} is promoted
OrderID string `json:"order_id"`
Courier *Courier `json:"courier"` // nil means "no value"
Total Cents `json:"total"`
Labels map[string]string `json:"labels"`
}
const src = `---
template: order.shipped
profile: orders
subject: "Order {{order_id}} is on its way"
preheader: "{{labels.eta | Arriving soon}}."
---
# On its way
Hi {{name | there}}, {{courier.first_name | your courier}} is bringing it.
Call them on {{courier.phone | the number in the app}}.
Order total: {{total}}.
::button{href="{{track_url}}" label="Track delivery"}
::
`
var orderShipped = lttr.MustCompile[OrderShipped](plain.MustKit(), "order.shipped", []byte(src))
func main() {
for _, tag := range orderShipped.Meta().Tags {
fmt.Printf("%-18s %-12s %s\n", tag.Path, tag.Type, tag.Pos)
}
r, err := lttr.NewRenderer(lttr.Config{
Kit: plain.MustKit(),
Profiles: []lttr.Profile{{Name: "orders", From: mail.Address{Name: "Example", Address: "orders@example.com"}}},
})
if err != nil {
log.Fatal(err)
}
msg, err := orderShipped.Render(r, lttr.Recipient{Address: "kim@example.com"}, OrderShipped{
Links: Links{TrackURL: "https://example.com/orders/A-1042"},
OrderID: "A-1042",
Total: 4250,
})
if err != nil {
log.Fatal(err)
}
fmt.Println()
fmt.Println(msg.Preheader)
fmt.Print(msg.Text)
}
order_id string 4:17
labels.eta string 5:13
name string 10:4
courier.first_name string 10:22
courier.phone string 11:14
total main.Cents 13:14
track_url string 15:16
Arriving soon.
Example
ON ITS WAY
Hi there, your courier is bringing it. Call them on the number in the
app.
Order total: $42.50.
Track delivery:
https://example.com/orders/A-1042
Template.Meta().Tags lists every tag and binding with the Go type it resolved to. name is not a field of OrderShipped, so it resolved to the recipient's name — see Search data, then the recipient. The recipient here has no name, the courier is nil and there is no eta label, so all three fallbacks were used.
Write a merge tag
A merge tag is {{path}} or {{path | fallback}}. The full grammar is in Insert merge tags. In short:
- A path is lower-case segments joined by dots:
[a-z_][a-z0-9_]*. - The fallback is bare text, or
"quoted"when it holds|,}or leading spaces. It is literal text: it can't hold another tag. \{{is a literal{{, and\|is the separator to use inside a GFM table cell.- Anything that starts with
{{but isn't a valid tag stays literal text, with the warningmalformed merge tag "{{ Name }}".
Name a path
With typed data, each segment of a path selects:
- a struct field by its JSON name. A field tagged
`json:"order_id"`isorder_id. Options after the comma (,omitempty) are ignored. - a struct field by its lower-cased name when it has no JSON name.
Phoneisphone, andTrackURLwithout a tag would betrackurl. Give fields JSON tags to choose readable names. - a promoted field of an embedded struct, as Go promotes it:
track_urlabove comes from the embeddedLinks. Embedded pointers to structs are followed too. - a map key in a
map[string]V:labels.etareadsLabels["eta"].
Pointers are followed at every step. Unexported fields and fields tagged `json:"-"` never match. A tag reads fields and map keys, never methods: a type's String method is how it prints, not something a path can name. (Kit templates can call methods on bound values; see Template checking.)
A path that doesn't resolve is a compile error at the tag. These come from lttr lint on a copy of a Quiet example:
| Error | Cause |
|---|---|
unknown name "otp_cod" (did you mean otp_code?) | The first segment is not a field of your type or of the recipient. A close match is suggested. |
unknown field "nme" in quiet.Courier (did you mean courier.name?) | A later segment is not a field of that struct. The suggestion is the whole corrected path. |
cannot descend into string at "courier.rating" | A path continues past a scalar, a slice or a map with non-string keys. |
ambiguous field "name" in main.T | Two embedded structs promote a field with the same name at the same depth. Go rejects the same selector; unlike encoding/json, a JSON tag on one of them does not break the tie. |
invalid path "Order" (did you mean order?) | A binding path that is not lower-case segments. (A tag with such a path is not a tag at all, just a malformed-tag warning, malformed merge tag "{{Order}}" (did you mean order?).) |
Search data, then the recipient
The first segment of a path is looked up in two places, in order:
- your data type
T, lttr.Recipient, the person the email goes to.
The first match wins. So {{name}} is the recipient's name unless T has a name field of its own. A Recipient has three fields (D39):
| Path | Field |
|---|---|
address | Address, the recipient's email address |
name | Name, the display name |
unsubscribe_url | UnsubscribeURL, the one-click unsubscribe URL |
Anything else your email shows per recipient, such as a first name or a region, belongs in your data type.
Print only scalars
A merge tag prints one value, so with typed data its path must end at a scalar:
- a string kind (
stringor a named string type), - an integer kind (
int,int64,uint8…), - any type implementing
fmt.Stringerwith a value receiver, such asCentsabove or Quiet'squiet.Money.
Floats, bools, structs that aren't Stringers, slices and maps are not scalars. A tag that ends at one is a compile error naming the type: {{courier}} is quiet.Courier, not a scalar. Format such values in Go, as a string field or a Stringer type, before they reach the template.
A value is printed with its String() method, as the string itself, or as a decimal integer.
Give a fallback
At render time, a tag has no value when:
- a nil pointer or a missing map key is on its path, or
- the value prints as the empty string.
Then its fallback is used:
Hi {{name | there}},
Your courier is {{courier.first_name | "on the way"}}.
A tag with no value and no fallback is a render error, with the tag's position: order.shipped:11:12: no value for {{deliver_to.city}}. The preheader is the exception: a tag there with no value renders as nothing.
Use untyped data
Compile also takes map[string]any, or any map with string keys, for data that has no Go type: a JSON payload, or a kit's YAML samples. Nothing is known about the data when the template compiles, so only the syntax and the kit's rules are checked then. Each path is read at render time instead (D50):
package main
import (
"encoding/json"
"fmt"
"log"
"net/mail"
"strings"
"github.com/sulv-io/lttr"
"github.com/sulv-io/lttr/kits/plain"
)
const src = `---
template: order.shipped
profile: orders
subject: "Order {{order_id}} is on its way"
preheader: "Arriving by {{eta}}."
---
# On its way
Hi {{name | there}}, order {{order_id}} comes to {{total}}.
It goes to {{deliver_to.city}}.
`
// No Go type: only the syntax and the kit's rules are checked here.
var orderShipped = lttr.MustCompile[map[string]any](plain.MustKit(), "order.shipped", []byte(src))
func main() {
r, err := lttr.NewRenderer(lttr.Config{
Kit: plain.MustKit(),
Profiles: []lttr.Profile{{Name: "orders", From: mail.Address{Name: "Example", Address: "orders@example.com"}}},
})
if err != nil {
log.Fatal(err)
}
to := lttr.Recipient{Address: "kim@example.com", Name: "Kim"}
for _, payload := range []string{
`{"order_id": "A-1042", "eta": "5:30 pm", "total": 42.5, "deliver_to": {"city": "Springfield"}}`,
`{"order_id": "A-1042", "eta": "5:30 pm", "total": 42.5}`,
`{"order_id": "A-1042", "eta": "5:30 pm", "total": 42.5, "deliver_to": "Springfield"}`,
`{"order_id": "A-1042", "eta": "5:30 pm", "total": {"amount": 42.5}, "deliver_to": {"city": "Springfield"}}`,
} {
var data map[string]any
if err := json.Unmarshal([]byte(payload), &data); err != nil {
log.Fatal(err)
}
msg, err := orderShipped.Render(r, to, data)
if err != nil {
fmt.Println("error:", err)
continue
}
for _, line := range strings.Split(msg.Text, "\n") {
if strings.HasPrefix(line, "Hi ") {
fmt.Println("ok:", line)
}
}
}
}
ok: Hi Kim, order A-1042 comes to 42.5. It goes to Springfield.
error: order.shipped:11:12: no value for {{deliver_to.city}}
error: order.shipped:11:12: no value for {{deliver_to.city}}
error: order.shipped:10:50: {{total}} is map[string]interface {}, not a scalar
The rules:
- A missing key is no value. The fallback is used, then the recipient for a first segment the map lacks (
{{name}}became Kim), then it is a render error at the tag. A path that runs into a string ("deliver_to": "Springfield") is missing too. - A map or list is an error, even with a fallback:
{{total}} is map[string]interface {}, not a scalar. - Floats and booleans print, because JSON and YAML decode to them: a float in its shortest form (
42.5), a boolean astrueorfalse. Typed data still refuses them. - Only the empty interface is untyped. A
map[string]anyoranyfield inside a typed struct is read the same way, from that field on. A field of a non-empty interface type, such asfmt.Stringer, stays typed and is checked at compile time. - Bindings still need their exact type, so untyped data cannot fill one:
receipt: :order is untyped data (order), want quiet.Receipt.
Meta().Tags reports an untyped tag's type as interface {}. Typed structs remain the recommended path: with a map, a typo in a path surfaces only when a message renders. Test every template that takes untyped data by rendering it.
Bind structured values
A binding, :key="path", passes a value to a component instead of printing it:
::invoice{:invoice="invoice"}
::
It resolves with the same path rules and the same scope as a merge tag, but it must resolve to exactly the Go type the component's schema names, as registered by the kit with kit.Types. A pointer on the path is followed, so a *Invoice field binds an Invoice. Any other type is a compile error naming both, such as receipt: :order is string, want quiet.Receipt. A named type is a type of its own: Quiet registers []quiet.Product as Products, and a field of type type Items []quiet.Product does not bind to it.
The component side is in Pass bindings.
Know how URLs are escaped
Merge tags in a url attribute, a link destination or an image source are escaped as URL parts at render time. The rule is about where the value sits:
- At the very start, a value is inserted as is.
href="{{track_url}}"passes a whole URL from your data through unchanged, so it can carry its own path and query. - After some literal text, in the path, query or fragment, a value is escaped. Before a
?it is escaped as a path segment; after a?it is escaped as a query value, with spaces as%20. - After some literal text, in the host (the URL so far has
//and no/,?or#after it), a value is not escaped, but it must be a whole DNS label of the host: a single label (ASCII letters, digits and-, not at either end), immediately preceded by literal//or., and immediately followed by literal text starting with., as inhttps://{{shop}}.example.com/. Anything else is a render error at the tag:merge value {{shop}} cannot form part of a url host. - A fallback follows the same rule as the value it replaces.
With q = a b&c=d/e?f#g@h, email = kim@example.com and shop = shop1, as rendered into a link:
| Template | Rendered |
|---|---|
https://x.example/p/{{q}} | https://x.example/p/a%20b&c=d%2Fe%3Ff%23g@h |
https://x.example/search?q={{q}} | https://x.example/search?q=a%20b%26c%3Dd%2Fe%3Ff%23g%40h |
mailto:{{email}} | mailto:kim@example.com |
https://{{shop}}.example.com/ | https://shop1.example.com/ |
https://{{q}}.example.com/ | render error: q is not a single DNS label |
https://accounts-{{shop}}.example.com/ | render error: shop isn't preceded by // or . |
https://{{shop}}/x | render error: no literal . follows the tag |
A tag that makes up the whole host, such as https://{{host}}/x, always fails, whatever its value. Pass the whole URL as the first part instead: href="{{shop_url}}". A value can never add a query parameter, change the path or fragment, or move the host.
The result is then checked like every URL. It must use https or http with a host, or mailto or tel with an address, and hold no whitespace; anything else is a render error, such as url "javascript:alert(1)": scheme "javascript" not allowed. Relative URLs are allowed only when Config.AllowRelativeURLs is set, for previews.
href="{{track_url}}". Writing href="https://example.com/{{path}}" with a path that contains / gives %2F, not a nested path.Leave an optional URL empty
A url attribute the schema doesn't require can be left unset: no link, no image. To leave it unset from data, give the tag an explicit empty fallback (D52):
::image{src="{{cover_url}}" alt="Your workspace" href="{{project_url |}}"}
::
With no project_url, the image renders without a link. The | is what makes it optional: href="{{project_url}}" with no value is still no value for {{project_url}}. And a required url that ends up empty is an error either way, reported by the component: image: src: url "": empty. Quiet's courier-job example writes its map the same way, ::map{src="{{map_url |}}" …}, so a job with no map image shows the map band's ground colour alone.
List a template's tags
Template.Meta().Tags is available on every compiled template, as in the first program. For a kit's samples, lttr tags prints the same list as path, Go type, tag or binding, and line:col, separated by tabs:
go run ./cmd/lttr tags -kit quiet -t order.out_for_delivery
destination string tag 5:25
eta string tag 5:44
order_id string tag 9:28
courier.first_name string tag 12:1
picked_up_at string tag 12:40
destination string tag 13:8
eta string tag 13:27
track_url string tag 15:31
order quiet.Receipt binding 21:1
deliver_to.name string tag 26:1
deliver_to.address string tag 27:1
courier.name string tag 30:1
courier.rating string tag 30:25
courier.vehicle string tag 31:1
Plain's samples render from untyped YAML data, so every tag there is interface {}. lttr tags knows only the samples of the kit you name; for your own templates, read Meta().Tags. See CLI.
Next steps
- Actions and spans for the
hrefvalues these URLs go into. - Compile errors for every path error in context.