liquid

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: AGPL-3.0 Imports: 15 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), ranges of at most 1,000 items and at most 4 MB of output.

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 (
	// 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 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 NewEngine

func NewEngine() *osteele.Engine

NewEngine returns a Liquid engine that can't read files. Every package that parses Liquid uses it.

osteele/liquid's include and render tags load other templates from the engine's template store, which by default reads files under the working directory: an email could print the server's files, and a template that renders itself recursed until the stack overflowed, killing the process. Both tags are removed, so using one is a parse error with its line, and the store holds no templates, so a tag added later can't read files either.

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)

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