Documentation
¶
Overview ¶
Package liquid renders personalization in subjects, preheaders and email bodies with Liquid (osteele/liquid): {{ first_name | default: "there" }}.
Email HTML escapes quotes and angle brackets, and editors write them as entities, so Prepare decodes entities inside {{ … }} and {% … %} before parsing. The composer's short form {{ first_name | "there" }} is accepted and read as default: "there". Rendering is bounded: no include or render (templates can't load other templates or files), literal ranges of at most 1,000 items, at most 4 MB of output, and a budget of steps, work and time for every render (budget.go), so a template someone can preview can't stall or exhaust the server.
One filter of ReputeCast's own: with_query sets a query parameter on a link, {{ upgrade_url | with_query: "offer", "FALL26" }}, whether or not the link already has a query (the Upgrade block's offer, Earn).
Index ¶
- Constants
- Variables
- func ExpandBlocks(src string) string
- func Fill(ctx context.Context, providers []RecipientData, workspaceID uuid.UUID, ...) map[string]any
- func FillBatch(ctx context.Context, providers []RecipientData, workspaceID uuid.UUID, ...) map[uuid.UUID]map[string]any
- func FirstNameFallback(l i18n.Lang) string
- func HasBlocks(src string) bool
- func Merge(vars map[string]any, extra map[string]any) map[string]any
- func Prepare(src string) string
- func RegisterBlock(name string, expand func(settings []byte) string)
- func RegisterTokens(t ...PersonalizationToken)
- func Render(src string, vars map[string]any) (string, error)
- func SourceFrom(ctx context.Context) string
- func UsedRoots(d RecipientData, src string) []string
- func Vars(email, firstName, lastName string, attributes map[string]any, ...) map[string]any
- func WithQuery(link, name, value string) string
- type CustomField
- type Issue
- type LiquidProblem
- type PersonalizationToken
- type Recipient
- type RecipientData
- type Template
- type Use
Constants ¶
const ( // MaxValue is the longest string a filter or capture may take or make. MaxValue = MaxOutput // MaxItems is the longest list or range a filter may take or make. MaxItems = 10_000 // MaxWork is how many bytes the filters and captures of one render may // read and make in total. MaxWork = 64 << 20 // MaxSteps is how many tags, outputs and loop passes one render may run. MaxSteps = 200_000 )
Every render runs on a budget. Anyone who can preview an email can make the server render Liquid they wrote, so a template must not be able to keep a core busy or fill the memory: a loop over a range read from a variable, three nested loops of 1,000, or a string that doubles with append or capture on every pass were all once enough to stall or kill the process. The budget counts what a render does and stops it with an error when it does too much:
- steps: every tag, every output and every pass of a loop;
- work: the bytes filters and captures read and make;
- the size of one value (MaxValue) and of one list (MaxItems);
- time, for what the counts don't see (contains on a long string).
The limits are far above what an email needs: a long digest takes a few thousand steps and well under a megabyte of work.
const ( // IssueSyntax: the template doesn't parse, so the email can't be // rendered for anyone. IssueSyntax = "syntax" // IssueUnknownField: the field doesn't exist, so every recipient gets // its fallback, or nothing. IssueUnknownField = "unknown_field" )
Issue kinds (Issue.Kind).
const MaxOutput = 4 << 20
MaxOutput is the largest rendered result, in bytes.
const MaxRange = 1000
MaxRange is the longest literal range a for loop may iterate.
Variables ¶
var ContactFields = []PersonalizationToken{
{Key: "first_name", Label: "First name", Kind: "contact", Fallback: "there"},
{Key: "last_name", Label: "Last name", Kind: "contact"},
{Key: "email", Label: "Email address", Kind: "contact"},
}
ContactFields are on every contact.
var ErrTooLarge = errors.New("the rendered email is larger than 4 MB")
ErrTooLarge is returned when rendering exceeds MaxOutput.
var ErrTooMuchWork = errors.New("the personalization does too much work to render: loops run too often, or values grow too large")
ErrTooMuchWork is returned when a render goes over its budget.
var MaxRenderTime = 2 * time.Second
MaxRenderTime is the longest one render may take.
var SystemFields = []PersonalizationToken{
{Key: "unsubscribe_url", Label: "Unsubscribe link", Kind: "system"},
{Key: "preferences_url", Label: "Email preferences link", Kind: "system"},
{Key: "view_in_browser_url", Label: "View in browser link", Kind: "system"},
}
SystemFields are links ReputeCast fills in per recipient at send time.
Functions ¶
func ExpandBlocks ¶
ExpandBlocks replaces the markers of registered blocks with what renders them. It is idempotent: the output has no markers left to expand.
func Fill ¶
func Fill(ctx context.Context, providers []RecipientData, workspaceID uuid.UUID, r Recipient, src string, vars map[string]any) map[string]any
Fill adds one reader's per-recipient variables (FillBatch) to vars.
func FillBatch ¶
func FillBatch(ctx context.Context, providers []RecipientData, workspaceID uuid.UUID, recipients []Recipient, src string) map[uuid.UUID]map[string]any
FillBatch is the per-recipient variables of every provider whose roots src uses, for a page of readers, by contact. A provider that fails adds nothing (its blocks hide).
func FirstNameFallback ¶
FirstNameFallback is the word a missing first name falls back to in an email written in l: "there" ("Hi there"), "bạn".
func Prepare ¶
Prepare decodes HTML entities inside Liquid delimiters and rewrites the short fallback form, so Liquid embedded in compiled HTML parses. Blocks that render per reader are expanded first (ExpandBlocks).
func RegisterBlock ¶
RegisterBlock adds a block expander. Expanders are pure: the output depends on the settings only.
func RegisterTokens ¶
func RegisterTokens(t ...PersonalizationToken)
RegisterTokens adds tokens other packages provide to every email's token catalog (Grow's referral.* tokens).
func SourceFrom ¶
SourceFrom is the template a RecipientData provider is filling in (FillBatch passes it along), for providers whose variables depend on how blocks were set up (the Recommendations block's picks).
func UsedRoots ¶
func UsedRoots(d RecipientData, src string) []string
UsedRoots are the roots of d a template's Liquid uses (a marker of a block counts as using its roots). Text outside Liquid never does.
Types ¶
type CustomField ¶
type CustomField struct {
Key, Label, Type string
}
CustomField is a workspace contact field (custom_fields).
type Issue ¶
type Issue struct {
Kind string `json:"kind" enum:"syntax,unknown_field"`
// Line and Message are a syntax error's line and the parser's words
// ("Line 3: unterminated tag…"), in English.
Line int `json:"line,omitempty"`
Message string `json:"message,omitempty"`
// Field is an unknown field ("frist_name"); HasFallback and Fallback
// say what it prints instead ("there").
Field string `json:"field,omitempty"`
HasFallback bool `json:"hasFallback,omitempty"`
Fallback string `json:"fallback,omitempty"`
}
Issue is a problem with an email's personalization (Check).
func Check ¶
Check finds what goes wrong when src is rendered (C8): syntax errors, which stop the email from rendering at all, and fields that don't exist, flagged even when they have a fallback, since {{ frist_name | default: "there" }} greets everyone with "there". fields are the fields that exist (Catalog keys); contact.*, the system links, loop and assigned variables and the per-recipient poll and survey links are always known. With no fields, only the syntax is checked.
type LiquidProblem ¶
LiquidProblem is a template error with its line.
func Validate ¶
func Validate(src string) []LiquidProblem
Validate parses a template and returns its problems (empty when it parses), in English. ValidateIn writes them in a reader's language.
func ValidateIn ¶
func ValidateIn(l i18n.Lang, src string) []LiquidProblem
ValidateIn is Validate with its problems in a reader's language.
type PersonalizationToken ¶
type PersonalizationToken struct {
Key string `json:"key" example:"first_name"`
Label string `json:"label" example:"First name"`
Kind string `json:"kind" enum:"contact,custom,system,referral,paid"`
// Fallback is the suggested default for contacts without a value.
Fallback string `json:"fallback,omitempty"`
// LabelText is the label's message when the package that registers the
// token keeps one: InLanguage writes it in the member's language.
LabelText i18n.Text `json:"-"`
}
PersonalizationToken is a personalization token offered by the composer.
func Catalog ¶
func Catalog(custom []CustomField) []PersonalizationToken
Catalog lists the tokens of a workspace: contact fields, its custom fields, then the system links.
func CatalogIn ¶
func CatalogIn(l i18n.Lang, custom []CustomField) []PersonalizationToken
CatalogIn is Catalog in a reader's language: the contact fields' and the system links' labels and the first-name fallback read in l. Custom fields are the workspace's own and keep their labels; tokens other packages register keep theirs.
func InLanguage ¶
func InLanguage(tokens []PersonalizationToken, l i18n.Lang) []PersonalizationToken
InLanguage writes the labels of tokens that keep their message in a language (the composer's token menu, in the member's language).
type Recipient ¶
type Recipient struct {
ContactID uuid.UUID
MessageID uuid.UUID
// EmailID is the automation email being sent (milestone emails read
// their reward from it); uuid.Nil for campaigns.
EmailID uuid.UUID
}
Recipient is one reader of a page of messages.
type RecipientData ¶
type RecipientData interface {
Roots() []string
Vars(ctx context.Context, workspaceID uuid.UUID, recipients []Recipient, roots []string) (map[uuid.UUID]map[string]any, error)
}
RecipientData adds variables that depend on the reader, for a page of readers at once: Grow's referral.* (the reader's link and progress), reward.* (milestone emails) and recommendations.* (the recommendations page link). Roots are the variable names it provides; Uses says which a template needs.
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template is parsed Liquid, ready to render many times (an email, once per recipient). Every render runs on its own budget (budget.go).