mjml

package
v1.4.0 Latest Latest
Warning

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

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

Documentation

Overview

Package mjml works with MJML documents on the server: a tolerant parser for outlines, warnings and wireframes, the server-side compiler (gomjml, MJML 4.15) used when content arrives as MJML only (API and automation sends), and head helpers that keep <mj-title>/<mj-preview> in step with the subject and preheader.

The composer compiles in the browser with mjml-browser (grapesjs-mjml); both engines target MJML 4 and parity is checked by tests.

Index

Constants

View Source
const (
	AttrVisible = "rc-visible"
	AttrName    = "rc-name"
	AttrPoll    = "rc-poll"
	AttrOmit    = "rc-omit"
	AttrShowOn  = "rc-show-on"
	// ShowOnWeb is a Web only block: it isn't part of the email.
	ShowOnWeb = "web"
)

AttrVisible, AttrName, AttrPoll and AttrOmit are ReputeCast's own attributes; AttrShowOn is a block's "Show on" (the publication website, design expansion phase 7): "email", "web", or absent for both.

View Source
const (
	MarkerIf = "<!--rc:if "
	MarkerFi = "<!--rc:fi "
)

Marker comments around a conditional block in compiled HTML.

View Source
const AttrSynced = "rc-synced"

AttrSynced marks a synced block in an email (review 2026-10, CO-11): the element, a section or a wrapper, is the workspace's synced block of that kind ("header", "footer", or a named block's key such as "b-0123456789ab", R4.A3), and is replaced whenever the block changes (internal/brandkit). Like every rc-* attribute it is left out of the compiled HTML.

Variables

This section is empty.

Functions

func ChangedSections

func ChangedSections(base, next string) []string

ChangedSections compares two documents and returns the labels of the sections of `next` that differ from `base` (added, edited or moved), plus the labels of sections removed from base.

func ConditionalID

func ConditionalID(n *Node) string

ConditionalID returns the id of a conditional element: one with a Visibility rule that doesn't show it to everyone. "" otherwise.

func ExpectedMarkers

func ExpectedMarkers(src string) []string

ExpectedMarkers lists the markers compiled HTML of src must carry, in order: one pair per conditional block PrepareCompile wraps.

func HeadMeta

func HeadMeta(src string) (title, preview string)

HeadMeta reads the title and preview text of a document.

func MarkSynced

func MarkSynced(block, kind string) (string, bool)

MarkSynced makes block, one MJML element, the synced block of a kind: it sets rc-synced on its outermost element. ok is false when block isn't a single section or wrapper.

func PrepareCompile

func PrepareCompile(src string) string

PrepareCompile turns a document into what the compilers get: rc-* attributes removed, Web only blocks (the post's, not the email's) and blocks marked rc-omit (shown in the editor only) left out, and conditional blocks wrapped in their markers. A document that doesn't parse is returned unchanged (the compiler reports its error). A block whose id appears twice is marked once, the first time: the composer gives a copied block an id of its own.

func RemoveAttr

func RemoveAttr(src string, n *Node, name string) (string, bool)

RemoveAttr removes an attribute of an element in the source.

func ReplaceSynced

func ReplaceSynced(src, kind, block string) (string, bool)

ReplaceSynced puts block in place of every element marked rc-synced="kind" (not inside another such element). block is the synced block's MJML, one element. It returns the document unchanged, and false, when nothing is marked, nothing changes or the document doesn't parse.

func SectionLabel

func SectionLabel(n *Node, index, total int) string

SectionLabel names a top-level body element: the ReputeCast marker when there is one, otherwise what it looks like.

func SectionWord

func SectionWord(l i18n.Lang, label string) string

SectionWord names a section label (Outline, SectionLabel) in a reader's language, in lower case as it reads inside a sentence: "chân thư" for "footer", "2 cột" for "2 columns". Labels it doesn't know, such as a block's own name, stay as they are.

func SetAttr

func SetAttr(src string, n *Node, name, value string) (string, bool)

SetAttr sets an attribute of an element in the source: it replaces the value or adds the attribute after the tag's name. Values are written double-quoted, escaped as html.EscapeString escapes them (spelled out, so that quotes visibly can't end the value: settings are JSON).

func SetAttrRaw

func SetAttrRaw(src string, n *Node, name, value string) (string, bool)

SetAttrRaw is SetAttr for values that hold single quotes on purpose (font stacks): only &, <, > and double quotes are escaped.

func SetHeadMeta

func SetHeadMeta(src, title, preview string) string

SetHeadMeta writes <mj-title> (the subject) and <mj-preview> (the preheader) into a document so the compiled HTML's title and hidden preview text always match the fields. Empty values remove the element. A document that doesn't parse is returned unchanged.

func StripMarkers

func StripMarkers(html string) string

StripMarkers removes the conditional markers from compiled HTML: the email every recipient would get if no block were conditional.

func SyncedKinds

func SyncedKinds(src string) []string

SyncedKinds lists the kinds of synced blocks a document holds, in the order they first appear.

func UnmarkSynced

func UnmarkSynced(src, kind string) (string, bool)

UnmarkSynced unlinks the elements marked rc-synced="kind": they keep their content as ordinary sections and no longer follow the block (it was deleted, R4.A3). It returns the document unchanged, and false, when nothing is marked or the document doesn't parse.

func UnwrapFragment

func UnwrapFragment(doc string) string

UnwrapFragment is the body elements of a document made by WrapFragment.

func WrapFragment

func WrapFragment(block string) string

WrapFragment puts body elements in a document so Parse reads them; UnwrapFragment takes them back out.

Types

type Attr

type Attr struct {
	Name  string
	Value string
}

Attr is one attribute with its decoded value.

type Fingerprint

type Fingerprint struct {
	// Links are the href of every <a>, in document order.
	Links []string
	// Images are the src of every <img>, in document order.
	Images []string
	// Words are the visible words of the body, in document order.
	Words []string
	// Markers are the conditional blocks' markers, in document order
	// ("if a1b2c3", "fi a1b2c3").
	Markers []string
}

Fingerprint is what an email shows and does, read from its HTML: its links, its images, its words and its conditional markers. The HTML of one MJML document from two compilers has one fingerprint even where the markup differs (gomjml and mjml-browser, checked by the parity tests).

func HTMLFingerprint

func HTMLFingerprint(src string) Fingerprint

HTMLFingerprint reads the fingerprint of compiled HTML. The head, styles, scripts and comments (Outlook's conditional comments included) carry no words; markers are comments of their own.

func (Fingerprint) Mismatch

func (a Fingerprint) Mismatch(b Fingerprint) string

Mismatch says how two fingerprints differ ("links", "images", "text", "conditional markers"), or "" when they agree.

func (Fingerprint) String

func (a Fingerprint) String() string

String writes a fingerprint for test failures.

type MJMLProblem

type MJMLProblem struct {
	Line    int    `json:"line"`
	Message string `json:"message"`
	Tag     string `json:"tag,omitempty"`
	// contains filtered or unexported fields
}

MJMLProblem is a compile error or warning with its line (0 when unknown). Message is in English; In writes it in a reader's language.

func Checked

func Checked(src, htmlSrc string) (out, mismatch string, errs []MJMLProblem)

Checked returns the HTML to store for an MJML document and the HTML a client compiled from it: the client's when it shows and does what the MJML says, the server's own compile otherwise (mismatch names what differed: links, images, text or conditional markers). Without HTML the server compiles; without MJML (an HTML-only email) the HTML is the source. errs is set when nothing trustworthy can be stored: the MJML doesn't compile and there is no HTML, or the HTML lacks the markers.

func Lint

func Lint(src string) []MJMLProblem

Lint returns layout warnings the MJML compiler doesn't report: images wider than their column (Outlook draws them at full width and breaks the layout) and columns adding up to more than their section. They are in English; LintIn writes them in a reader's language.

func LintIn

func LintIn(lang i18n.Lang, src string) []MJMLProblem

LintIn is Lint in a reader's language, with numbers in their region's format.

func (MJMLProblem) In

func (p MJMLProblem) In(l i18n.Lang) string

In writes a compile problem or a layout warning in a reader's language. What the compiler reports in its own words stays in English after the line.

type MJMLThumbItem

type MJMLThumbItem struct {
	Kind   string          `` /* 140-byte string literal not displayed */
	H      int             `json:"h,omitempty"`
	W      int             `json:"w,omitempty"`
	Accent bool            `json:"accent,omitempty"`
	Row    []MJMLThumbItem `json:"row,omitempty"`
}

MJMLThumbItem is one part of a template's thumbnail in the gallery, a miniature email (Composer and ComposerEmpty boards): a block of height H (px) and width W (% of the thumbnail; 0 = full), an accent pill for buttons, or a row of blocks for columns. Kind says what it stands for.

func Thumb

func Thumb(src string) []MJMLThumbItem

Thumb derives the gallery's miniature email from a document: the header (logo and links), a block for a hero image, a row of blocks for columns, lines for headings and text, a pill for a button, and the footer. The header and the footer frame it; between them it keeps at most five parts and stops at the first one that doesn't fit, so no part is cut off.

type Merge

type Merge struct {
	// MJML is mine with their sections (and head) put in. Its head has no
	// <mj-title> or <mj-preview>: they follow the subject and preheader,
	// which are merged on their own (SetHeadMeta puts them back).
	MJML string
	// Theirs are the sections taken from theirs, in mine's positions.
	Theirs []MergedSection
	// Head is the inner MJML of their mj-head (styles, fonts, attributes)
	// when theirs changed it and mine didn't.
	Head string
}

Merge is a three-way merge of two edits of the same version, section by section (review 2026-10, CO-10): when two people changed different sections, each keeps theirs.

func MergeSections

func MergeSections(base, theirs, mine string) (Merge, bool)

MergeSections merges theirs and mine, both edited from base, when they changed different sections. ok is false when they changed the same section (or the head) differently, or added, removed or moved sections: a person then chooses.

type MergedSection

type MergedSection struct {
	Index int    `json:"index"`
	Label string `json:"label"`
	MJML  string `json:"mjml"`
}

MergedSection is a section a merge took from the other side.

type Node

type Node struct {
	Tag      string
	Attrs    []Attr
	Children []*Node
	// Inner is the raw content of ending tags (mj-text, mj-button, mj-raw…),
	// which hold HTML rather than MJML elements.
	Inner string
	// Marker is the ReputeCast block a preceding <!-- rc:… --> comment names
	// ("footer", "header-logo"), empty otherwise.
	Marker string
	// Line is the 1-based line of the opening tag.
	Line int
	// Start and End are byte offsets of the element in the source.
	Start, End int
}

Node is one element of an MJML document.

func Body

func Body(root *Node) *Node

Body returns the <mj-body> of a document, or nil.

func Head(root *Node) *Node

Head returns the <mj-head> of a document, or nil.

func Parse

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

Parse reads an MJML document and returns its <mjml> root. It is lenient about whitespace, attribute quoting, comments and void tags, and reports tags that are never closed with their line.

func (*Node) Attr

func (n *Node) Attr(name string) string

Attr returns an attribute value or "".

func (*Node) Find

func (n *Node) Find(tag string) *Node

Find returns the first descendant (or n itself) with the tag.

func (*Node) Get

func (n *Node) Get(name string) (string, bool)

Get returns an attribute value and whether it is set.

func (*Node) Walk

func (n *Node) Walk(fn func(node *Node, path []int))

Walk calls fn for n and every descendant, depth first, with the path of element indices from n.

type ParseError

type ParseError struct {
	Line    int
	Message string
	// contains filtered or unexported fields
}

ParseError is a syntax problem with its line. Message is in English; In writes it in a reader's language.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) In

func (e *ParseError) In(l i18n.Lang) string

In writes the problem in a reader's language: "Line 3: unclosed <mj-section>", "Dòng 3: <mj-section> chưa được đóng".

type Result

type Result struct {
	HTML     string
	Errors   []MJMLProblem
	Duration time.Duration
}

Result is the outcome of a server-side compile.

func Compile

func Compile(src string) Result

Compile renders MJML to HTML with gomjml, the server-side twin of the composer's mjml-browser. It is used when content arrives as MJML only (the API, automations); the composer stores the HTML it compiled itself.

func CompileIn

func CompileIn(l i18n.Lang, src string) Result

CompileIn is Compile with its problems written in a reader's language.

type Section

type Section struct {
	// Index is the position among mj-body's elements (comments excluded).
	Index int    `json:"index"`
	Tag   string `json:"tag"`
	// Label names the section the way the layer tree does: "header", "hero",
	// "2 columns", "text", "footer".
	Label string `json:"label"`
	// Marker is the ReputeCast block it was inserted from ("footer"), if any.
	Marker string `json:"marker,omitempty"`
	Line   int    `json:"line"`
	// Hash fingerprints the section's source, to tell which sections changed
	// between two versions.
	Hash string `json:"-"`
}

Section is one top-level block of <mj-body>.

func Outline

func Outline(src string) ([]Section, error)

Outline lists the sections of a document's body with readable labels.

type Verdict

type Verdict struct {
	// OK is true when the HTML shows and does what the MJML says.
	OK bool
	// Mismatch names what differs ("links", "text", "conditional markers").
	Mismatch string
	// HTML is the server's own compile of the MJML, to store instead when
	// the HTML doesn't match; empty when the server couldn't compile it.
	HTML string
	// Errors are the server compile's errors, if any.
	Errors []MJMLProblem
}

Verdict is the outcome of checking a client's HTML against its MJML.

func Verify

func Verify(src, htmlSrc string) Verdict

Verify checks HTML a client compiled from src against the server's own compile of src (gomjml, with the conditional markers PrepareCompile adds). When gomjml can't compile a document that parses, the markers the MJML needs are still checked; one that doesn't parse is refused.

Jump to

Keyboard shortcuts

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