liquid

package
v1.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 23 Imported by: 0

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

View Source
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.

View Source
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).

View Source
const MaxOutput = 4 << 20

MaxOutput is the largest rendered result, in bytes.

View Source
const MaxRange = 1000

MaxRange is the longest literal range a for loop may iterate.

Variables

View Source
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.

View Source
var ErrTooLarge = errors.New("the rendered email is larger than 4 MB")

ErrTooLarge is returned when rendering exceeds MaxOutput.

View Source
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.

View Source
var MaxRenderTime = 2 * time.Second

MaxRenderTime is the longest one render may take.

View Source
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

func ExpandBlocks(src string) string

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

func FirstNameFallback(l i18n.Lang) string

FirstNameFallback is the word a missing first name falls back to in an email written in l: "there" ("Hi there"), "bạn".

func HasBlocks

func HasBlocks(src string) bool

HasBlocks reports whether src has a marker of a registered block.

func Merge

func Merge(vars map[string]any, extra map[string]any) map[string]any

Merge adds a reader's per-recipient variables to vars.

func Prepare

func Prepare(src string) string

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

func RegisterBlock(name string, expand func(settings []byte) string)

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 Render

func Render(src string, vars map[string]any) (string, error)

Render parses and renders src once.

func SourceFrom

func SourceFrom(ctx context.Context) string

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.

func Vars

func Vars(email, firstName, lastName string, attributes map[string]any, links map[string]string) map[string]any

Vars builds the variables of one recipient: contact fields, custom fields (attributes) and the per-recipient links. Contact fields are also available as contact.first_name.

func WithQuery

func WithQuery(link, name, value string) string

WithQuery is the with_query filter: the link with the query parameter name set to value. Anything that isn't a web link comes back as it is.

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

func Check(src string, fields []string) []Issue

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

type LiquidProblem struct {
	Line    int    `json:"line"`
	Message string `json:"message"`
}

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).

func Parse

func Parse(src string) (*Template, error)

Parse prepares and parses src. Every package that parses Liquid uses it, so no template renders without a budget or reads files.

func (*Template) Render

func (t *Template) Render(vars map[string]any) (string, error)

Render fills the template in with vars. The result is at most MaxOutput bytes; a template that goes over its budget fails with ErrTooMuchWork.

type Use

type Use struct {
	Key         string `json:"key"`
	Fallback    string `json:"fallback,omitempty"`
	HasFallback bool   `json:"hasFallback"`
	Count       int    `json:"count"`
}

Use is a variable a template prints, with its fallback.

func Uses

func Uses(src string) []Use

Uses lists the variables printed with {{ … }}, in order of first use. Blocks (ExpandBlocks) aren't expanded: their Liquid is ReputeCast's own, and what a person typed in their settings stays in the marker.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL