Documentation
¶
Overview ¶
Package component renders the MJML component tree: every body and head component of MJML 5.4, the per-render state the renderer accumulates from the document head, the validation applied to a parsed document before it is rendered, and the contract a host implements to add a component of its own.
The package is exported because the root mjmlgo package and custom components share it. Part of what it exports is frozen API: the render context fields keep their meaning and their type, methods may be added and fields may not change meaning. The exact frozen set is listed under "What is API" below; changing any of it is a breaking change.
What is API ¶
The supported surface is what an embedder needs to inspect a render or to build a component against:
- RenderContext and its exported fields: the state a component reads while rendering, and the structure the parser fills from the head (mj-attributes, mj-class, mj-font, mj-html-attributes, styles, preview, title, breakpoint, language and direction). CustomComponents holds the components the renderer was configured with.
- The types those fields are declared with: AttributeMap, Stylesheet, Rule, MediaRule, Style, HTMLAttributeSelector, HTMLAttribute, ComponentHeadStyle and Component.
- Component, ChildComponent and AttributeValidator, the custom-component contract (see below).
- InitComponent, which validates the attributes the author wrote and then fills in the component's defaults.
- ValidateDocument, which checks tag names, nesting, attribute values and mj-class references against MJML's own tables before rendering starts.
- Error, ErrorKind and NewError, the structured failure every validation, parse and component-registration site constructs. Callers inspect Kind, Path, Attribute and Value; errors.Is keeps matching ErrValidation.
- IsBuiltinTag, which reports whether a tag is already implemented here (every component, the head handlers, mj-all, mj-class and mj-include) and so cannot be used by a custom component.
- RenderChildren and RenderChildrenInTableBody, which render a container's children with the built-in or registered components they belong to (the second for children that sit directly in a table body, where raw content needs the raw-block markers), and IsContentTag, which reports whether a built-in tag is one of the content components a container may declare.
- RenderContext.AddComponentHeadStyle, AddInstanceComponentHeadStyle, AddMediaQuery and AddFluidOnMobileClass, the head-contribution mechanisms the built-in components use.
- DefaultIDGenerator and the TagName constants.
Custom components ¶
A host adds an element without patching this repository by implementing Component and registering it on a renderer (mjmlgo.WithComponents):
- Name is the tag. It must not be empty, must not be registered twice on the same renderer and must not shadow a built-in element; such a renderer is rejected with a *Error of kind KindInvalidComponent.
- AllowedAttributes declares every accepted attribute with its validator. An undeclared author attribute and a value its validator rejects are validation errors carrying the element path, exactly as for a built-in component. css-class and mj-class are universal and need no entry, and a nil validator accepts every value. The returned map is read-only: the renderer may share one table across renders, so it must not be modified.
- DefaultAttributes returns the values applied when the author wrote none, after author attributes have been validated. Per-tag defaults from mj-attributes and attributes from mj-class are applied before those, so a custom tag takes part in the document's default cascade.
- Render writes the element's HTML from the render context and the node. Both are the values a built-in component receives, so a custom component needs no access to package internals.
A custom component is a leaf unless it also implements ChildComponent, whose AllowedChildren lists the child tags it accepts; a component without it rejects every child. A custom tag is accepted where content goes - as a direct child of mj-body, mj-column or mj-hero - and not where a layout element is expected. Registration is per renderer: there is no global registry, and two renderers in one process may know different tags.
A ChildComponent renders the children it accepted with RenderChildren (or RenderChildrenInTableBody when they sit directly in a <tbody>), which validates each child's attributes, applies its defaults and dispatches it to the built-in or registered component that renders it. The container owns all markup around its children, so it can render them into a buffer first and write its own wrapper around finished HTML. Its declared child list is closed: registration rejects a container that declares a child which is neither a content component (IsContentTag) nor a component registered on the same renderer. The built-in container renderers still do not descend into a custom tag - the component calls RenderChildren itself.
A container contributes CSS to the head through the mechanisms the built-in components use: AddComponentHeadStyle for a named block (de-duplicated by name), AddInstanceComponentHeadStyle for a per-instance block that must never be merged, AddMediaQuery for class rules inside the document's breakpoint media query, and AddFluidOnMobileClass for MJML's fluid-on-mobile rule on a class of its own. All four keep registration order, so a document's head is deterministic across renders. Classes that want the same rule are emitted as one selector list - `.a, .b { ... }` - which is how MJML 5 writes them; MediaQueryGroups exposes that grouping.
example/customcomponent is the in-repo example of the whole contract: Badge is a leaf, Notice a container with head styles.
What is not API ¶
The concrete components - MJML, MJMLSection, MJMLColumn, ... - are exported only so the renderer can dispatch to them. Their markup, their default attribute tables and their call order are implementation details; they change whenever matching the reference implementation requires it.
ErrValidation is still exported as the sentinel the element, attribute, value, child and mj-class kinds match with errors.Is; ErrMJMLBadlyFormatted, MergeOutlookConditionals, RemoveNonNumeric, RawBlockStartMarker, RawBlockEndMarker and StripRawBlockMarkers are exported to wire the packages together. The markers are what RenderChildrenInTableBody writes and the renderer strips; no parser needs them any more, they are all that is left of the mechanism that kept raw content in place. They are not meant to be called from outside, and may be changed or unexported.
What user code must not touch ¶
Rendering keeps private markers on nodes. They are internal conveniences, not part of the MJML language, and user code must not set, read or depend on them:
- The parser protects the content of raw-content elements (mj-text, mj-button, mj-raw, ...) with CDATA sections so arbitrary markup survives encoding/xml. The protection is removed again while parsing and never appears in node.Node.Content.
- mj-group marks its child columns with the synthetic attribute mobileWidth="mobileWidth" so the column renderer knows it is inside a group. Document validation rejects that attribute on input; only the group renderer may set it.
- node.Node.Parent is parser bookkeeping. Components receive the node to render and must walk Children instead of ascending Parent; see package node.
A RenderContext also carries unexported state: the two font-family values that accordion titles and texts inherit from the element they are rendered in. That is contextual rendering state, not configuration.
Index ¶
- Constants
- Variables
- func DefaultIDGenerator() string
- func InitComponent(ctx *RenderContext, comp Component, n *node.Node) error
- func IsBuiltinTag(tag string) bool
- func IsContentTag(tag string) bool
- func MergeOutlookConditionals(content string) string
- func RemoveNonNumeric(s string) string
- func RenderChildren(ctx *RenderContext, w io.Writer, n *node.Node) error
- func RenderChildrenInTableBody(ctx *RenderContext, w io.Writer, n *node.Node) error
- func StripRawBlockMarkers(html string) string
- func ValidateDocument(ctx *RenderContext, root *node.Node) error
- type AttributeMap
- type AttributeValidator
- type ChildComponent
- type Component
- type ComponentHeadStyle
- type Error
- type ErrorKind
- type HTMLAttribute
- type HTMLAttributeSelector
- type MJML
- type MJMLAccordion
- type MJMLAccordionElement
- type MJMLAccordionText
- type MJMLAccordionTitle
- type MJMLBody
- type MJMLButton
- type MJMLCarousel
- type MJMLCarouselImage
- type MJMLColumn
- type MJMLComponentName
- type MJMLDivider
- type MJMLGroup
- type MJMLHead
- type MJMLHero
- type MJMLImage
- type MJMLNavbar
- type MJMLNavbarLink
- type MJMLRaw
- type MJMLSection
- type MJMLSocial
- type MJMLSocialElement
- type MJMLSpacer
- type MJMLTable
- type MJMLText
- type MediaQueryGroup
- type MediaRule
- type RenderContext
- func (c *RenderContext) AddComponentHeadStyle(name string, style func(breakpoint string) string)
- func (c *RenderContext) AddFluidOnMobileClass(className string)
- func (c *RenderContext) AddInstanceComponentHeadStyle(name string, style func(breakpoint string) string)
- func (c *RenderContext) AddMediaQuery(className string, declarations []string)
- func (c RenderContext) MediaQueryGroups() []MediaQueryGroup
- type Rule
- type Style
- type Stylesheet
Constants ¶
const ( RawBlockStartMarker = "<!--mjmlgo-raw-start-->" RawBlockEndMarker = "<!--mjmlgo-raw-end-->" )
RawBlockStartMarker and RawBlockEndMarker wrap raw content that a container renders directly inside a <tbody>, so its position stays explicit in the markup. They are removed from the final output by StripRawBlockMarkers.
Variables ¶
var ErrMJMLBadlyFormatted = errors.New("MJML badly formatted")
var ErrValidation = errors.New("failed validation")
Functions ¶
func DefaultIDGenerator ¶
func DefaultIDGenerator() string
DefaultIDGenerator returns the MJML-shaped id used when no generator is configured: 16 lowercase hex characters from crypto/rand. MJML itself uses a random value here, so documents are not byte-for-byte reproducible unless a caller injects its own generator.
func InitComponent ¶
func InitComponent(ctx *RenderContext, comp Component, n *node.Node) error
InitComponent prepares n for rendering with comp: it validates the attributes the author wrote and then sets the component's default for every attribute the element does not already have. It is the first thing every body-component renderer calls for an element.
func IsBuiltinTag ¶
IsBuiltinTag reports whether tag is one of the elements this package implements: every body and head component, mj-all, mj-class, mj-include and the document elements. A custom component must not use such a tag, because registration would shadow the built-in element instead of extending the language.
func IsContentTag ¶
IsContentTag reports whether tag is a built-in content component: one a custom container may declare as a child, because RenderChildren can render it. The layout components (mj-section, mj-wrapper, mj-group, mj-column) and the head components are not content tags; a custom component occupies a content position, and its children do too.
func MergeOutlookConditionals ¶
MergeOutlookConditionals joins adjacent Outlook conditional blocks exactly like MJML's mergeOutlookConditionnals helper: the closing marker of a block, the whitespace after it and the opening marker of the next "mso | IE" block are dropped, so contiguous Outlook fragments form one conditional comment.
It is implemented as a single scan instead of a regular expression over the whole document, which keeps it allocation-free apart from the result buffer.
func RemoveNonNumeric ¶
func RenderChildren ¶
RenderChildren renders every child of n into w, in document order. It is how a custom container renders the children it accepted: each child is dispatched to the built-in component that renders its tag or to the custom component registered for it, with its author attributes validated and its defaults applied first - exactly what the built-in content containers do for their children. A child outside the container's AllowedChildren is a KindDisallowedChild error carrying the element path, so a component that renders without prior validation still enforces its own contract.
The component owns all markup around the children. It may render them straight into w, or into a buffer of its own first so every child is rendered before the wrapper is written:
var children strings.Builder
if err := component.RenderChildren(ctx, &children, n); err != nil {
return err
}
// ... write the wrapper and children.String() ...
An mj-raw child is rendered verbatim, the way the built-in containers render raw content outside a table body (mj-body, mj-head, mj-section, mj-wrapper, mj-group, mj-accordion-element, mj-social and mj-navbar). A container whose children sit directly inside a <tbody> calls RenderChildrenInTableBody instead, which states that position in the markup with the raw-block markers.
func RenderChildrenInTableBody ¶
RenderChildrenInTableBody is RenderChildren for a container whose children sit directly inside a <tbody> - the position the built-in column and hero put their children in. It wraps an mj-raw child in the raw-block markers, which state that position in the markup and are stripped by the renderer before the caller sees the document.
The markers are internal transport, not a styling mechanism: the inline stage matches selectors against the emitted markup itself and styles a raw block where it stands, so it needs no protection from any parser and both helpers produce the same document. Choosing the wrong helper is therefore a documentation mistake, not a styling difference - but use this one when your children really do sit in a table body, because that is the contract the markers state.
func StripRawBlockMarkers ¶
StripRawBlockMarkers removes the raw-block markers from rendered HTML. They are internal transport for RenderChildrenInTableBody and are not output.
func ValidateDocument ¶
func ValidateDocument(ctx *RenderContext, root *node.Node) error
ValidateDocument checks the parsed tree against MJML's dependency table and every component's allowedAttributes before anything is rendered. It is the fail-fast counterpart of mjml-validator's soft warnings: unknown elements, disallowed children, unknown attributes and invalid attribute values are hard errors that carry the element path.
Types ¶
type AttributeMap ¶
AttributeMap holds a set of MJML attribute values keyed by attribute name.
type AttributeValidator ¶
AttributeValidator checks one attribute value written by the document author. It returns nil when the value is acceptable and an error describing why it is not otherwise. The error text is embedded in the structured *Error the validator site returns, so it should name what was rejected and why.
A nil validator accepts every value; leave an attribute out of the AllowedAttributes map to reject it instead.
type ChildComponent ¶
ChildComponent is a Component that accepts child elements. A component that does not implement it is a leaf: any child element under its tag is rejected as a disallowed child.
AllowedChildren returns the child tag names the component accepts, in the order they are reported in error messages. Declaring children makes the tag a container for validation, and registration rejects a declaration no component can render: every declared child must be a built-in content component (see IsContentTag) or a custom component registered on the same renderer.
The container renders its children with RenderChildren, which validates each child's attributes, applies its defaults and dispatches it, and contributes head CSS with RenderContext.AddComponentHeadStyle, AddMediaQuery and AddFluidOnMobileClass. Render is still the render entry point: it writes the wrapper markup and calls RenderChildren where the children belong.
type Component ¶
type Component interface {
// Name is the element's tag name, for example "mj-badge". It must be
// non-empty, must not be registered twice on one renderer and must not
// shadow a built-in MJML element.
Name() string
// AllowedAttributes maps every attribute the component accepts to its
// validator. An author attribute that is not in the map is rejected; the
// universal css-class and mj-class attributes are accepted without an entry.
// A nil validator accepts every value. The returned map is read-only: the
// renderer may share one table across renders, so a component must not
// modify the map it returns.
AllowedAttributes() map[string]AttributeValidator
// DefaultAttributes returns the values to apply for attributes the author
// did not write. They are applied after author attributes have been
// validated, like a built-in component's defaults.
DefaultAttributes(ctx *RenderContext) map[string]string
// Render writes the element's HTML to w. Returning an error stops the
// render.
Render(ctx *RenderContext, w io.Writer, n *node.Node) error
}
Component is one MJML element that knows how to render itself. The renderer looks a component up by tag name, validates the element's author attributes with InitComponent and then calls Render, which writes the element's HTML to w.
It is the custom-component contract: a host implements it and registers the component on a renderer with mjmlgo.WithComponents. A registered tag is a first-class element - it is validated like a built-in one, receives the defaults declared in mj-attributes and mj-class, and renders at its document position with Render. The node the renderer hands to Render is the one the built-in components receive: attribute defaults are already applied and the children are the parsed child elements. A component that implements it is a leaf unless it also implements ChildComponent.
type ComponentHeadStyle ¶
ComponentHeadStyle is one component-generated stylesheet. Style is rendered with the document breakpoint and emitted verbatim into the head.
type Error ¶
type Error struct {
// Kind is the classification of the failure.
Kind ErrorKind
// Path is the element path from the document root to the offending element,
// e.g. []string{"mj-body", "mj-section", "mj-text"}. The root <mjml>
// element is omitted, like the paths in error messages always have been. A
// document-level failure that happens before an element exists uses the
// document element it failed to build. Every site in this package supplies
// a non-empty Path; the constructor does not enforce it for hand-built
// errors.
Path []string
// Attribute is the attribute that failed, when the failure is about one.
Attribute string
// Value is the offending attribute value, or the offending element name for
// element-level kinds.
Value string
// Err is the underlying cause. It is nil for failures that need no detail.
Err error
}
Error is the structured failure returned by every validation and parse site. It carries the offending element's path as data, the attribute and value when they are what failed, and the underlying cause.
Error text is for humans and may change; callers should inspect Kind, Path, Attribute and Value, or use errors.Is/errors.As. Unwrap exposes Err, so errors.Is works for the sentinels (ErrValidation, ErrIncludeCycle, ...) that used to be returned on their own.
func NewError ¶
NewError is the single constructor for a structured failure. Every validation and parse site reports through it, so the kind set and the shape of the error cannot drift between sites.
func (*Error) Error ¶
Error renders the failure for people. The format follows the messages this implementation has always emitted, so logs keep their meaning; callers that need to branch on a failure use Kind or errors.Is instead.
type ErrorKind ¶
type ErrorKind string
ErrorKind classifies why a document was rejected. The set is closed: every validation and parse failure this package reports is one of these kinds, so a caller can branch on it instead of matching error text.
const ( // KindUnknownElement reports an element that is not part of MJML. KindUnknownElement ErrorKind = "unknown element" // KindUnknownAttribute reports an attribute that is not allowed on its // element. KindUnknownAttribute ErrorKind = "unknown attribute" // KindInvalidValue reports an attribute value that does not match MJML's // type for it, or a required attribute that is missing. KindInvalidValue ErrorKind = "invalid value" // KindDisallowedChild reports an element nested where MJML's dependency // table does not allow it. KindDisallowedChild ErrorKind = "disallowed child" // KindUnknownIncludeType reports an mj-include whose type is not mjml, html // or css. KindUnknownIncludeType ErrorKind = "unknown include type" // KindUndefinedMJClass reports an mj-class reference to a class the document // does not declare in mj-attributes. KindUndefinedMJClass ErrorKind = "undefined mj-class" // KindParseFailure reports a document that could not be read into a // renderable MJML tree: malformed XML, no root element, no mj-body, or an // mj-include that cannot be resolved. Include I/O failures are in this // kind because they are failures to assemble the document, not // attribute validation. KindParseFailure ErrorKind = "parse failure" // KindInvalidComponent reports a custom component the renderer refuses to // register: a nil component, an empty tag, a tag registered twice, or a tag // that shadows a built-in element. It is a renderer-configuration failure // rather than a document failure, so it does not match ErrValidation. There // is no offending document element: Path names the tag that cannot be // registered, or the document element when the component has no tag, and // Value is the tag when there is one. KindInvalidComponent ErrorKind = "invalid component" )
type HTMLAttribute ¶
HTMLAttribute is one attribute set by <mj-html-attribute>.
type HTMLAttributeSelector ¶
type HTMLAttributeSelector struct {
Path string
Attributes []HTMLAttribute
}
HTMLAttributeSelector is one <mj-selector> target and the attributes it sets.
type MJML ¶
type MJML struct{}
func (MJML) AllowedAttributes ¶
func (m MJML) AllowedAttributes() map[string]AttributeValidator
func (MJML) DefaultAttributes ¶
func (m MJML) DefaultAttributes(_ *RenderContext) map[string]string
type MJMLAccordion ¶
type MJMLAccordion struct{}
MJMLAccordion renders mj-accordion (node_modules/mjml-accordion/lib/Accordion.js).
func (MJMLAccordion) AllowedAttributes ¶
func (a MJMLAccordion) AllowedAttributes() map[string]AttributeValidator
func (MJMLAccordion) DefaultAttributes ¶
func (a MJMLAccordion) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLAccordion) Name ¶
func (a MJMLAccordion) Name() string
func (MJMLAccordion) Render ¶
func (a MJMLAccordion) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLAccordionElement ¶
type MJMLAccordionElement struct{}
MJMLAccordionElement renders mj-accordion-element.
func (MJMLAccordionElement) AllowedAttributes ¶
func (e MJMLAccordionElement) AllowedAttributes() map[string]AttributeValidator
func (MJMLAccordionElement) DefaultAttributes ¶
func (e MJMLAccordionElement) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLAccordionElement) Name ¶
func (e MJMLAccordionElement) Name() string
func (MJMLAccordionElement) Render ¶
func (e MJMLAccordionElement) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLAccordionText ¶
type MJMLAccordionText struct{}
MJMLAccordionText renders mj-accordion-text.
func (MJMLAccordionText) AllowedAttributes ¶
func (t MJMLAccordionText) AllowedAttributes() map[string]AttributeValidator
func (MJMLAccordionText) DefaultAttributes ¶
func (t MJMLAccordionText) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLAccordionText) Name ¶
func (t MJMLAccordionText) Name() string
func (MJMLAccordionText) Render ¶
func (t MJMLAccordionText) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLAccordionTitle ¶
type MJMLAccordionTitle struct{}
MJMLAccordionTitle renders mj-accordion-title.
func (MJMLAccordionTitle) AllowedAttributes ¶
func (t MJMLAccordionTitle) AllowedAttributes() map[string]AttributeValidator
func (MJMLAccordionTitle) DefaultAttributes ¶
func (t MJMLAccordionTitle) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLAccordionTitle) Name ¶
func (t MJMLAccordionTitle) Name() string
func (MJMLAccordionTitle) Render ¶
func (t MJMLAccordionTitle) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLBody ¶
type MJMLBody struct{}
func (MJMLBody) AllowedAttributes ¶
func (b MJMLBody) AllowedAttributes() map[string]AttributeValidator
func (MJMLBody) DefaultAttributes ¶
func (b MJMLBody) DefaultAttributes(_ *RenderContext) map[string]string
type MJMLButton ¶
type MJMLButton struct{}
func (MJMLButton) AllowedAttributes ¶
func (b MJMLButton) AllowedAttributes() map[string]AttributeValidator
func (MJMLButton) DefaultAttributes ¶
func (b MJMLButton) DefaultAttributes(ctx *RenderContext) map[string]string
func (MJMLButton) Name ¶
func (b MJMLButton) Name() string
func (MJMLButton) Render ¶
func (b MJMLButton) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLCarousel ¶
type MJMLCarousel struct{}
MJMLCarousel renders mj-carousel. The markup and the generated `mj-carousel-<id>` stylesheet follow mjml-carousel 5.4.1 (node_modules/mjml-carousel/lib/Carousel.js): a downlevel-revealed non-Outlook block holding one hidden radio per image, the optional thumbnails and the images table, plus an Outlook-only fallback that shows the first image.
MJML gives every carousel a random 16-character hex id that ends up in ids, class names and the generated selectors. The id comes from the render's configured generator (see RenderContext.nextComponentID); the parity harness treats a 16-hex id as an opaque value.
func (MJMLCarousel) AllowedAttributes ¶
func (c MJMLCarousel) AllowedAttributes() map[string]AttributeValidator
func (MJMLCarousel) DefaultAttributes ¶
func (c MJMLCarousel) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLCarousel) Name ¶
func (c MJMLCarousel) Name() string
func (MJMLCarousel) Render ¶
func (c MJMLCarousel) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLCarouselImage ¶
type MJMLCarouselImage struct{}
MJMLCarouselImage renders mj-carousel-image, the only child of mj-carousel (node_modules/mjml-carousel/lib/CarouselImage.js). One image contributes a slide in the images table and an entry in the thumbnail strip; the hidden radio input in front of the content is rendered by mj-carousel.
The image is never rendered on its own, so unlike the other components it does not implement Component: mj-carousel calls the parts and initCarouselImage applies the attribute defaults and validation.
func (MJMLCarouselImage) AllowedAttributes ¶
func (i MJMLCarouselImage) AllowedAttributes() map[string]AttributeValidator
func (MJMLCarouselImage) DefaultAttributes ¶
func (i MJMLCarouselImage) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLCarouselImage) Name ¶
func (i MJMLCarouselImage) Name() string
type MJMLColumn ¶
type MJMLColumn struct{}
func (MJMLColumn) AllowedAttributes ¶
func (c MJMLColumn) AllowedAttributes() map[string]AttributeValidator
func (MJMLColumn) DefaultAttributes ¶
func (c MJMLColumn) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLColumn) Name ¶
func (c MJMLColumn) Name() string
func (MJMLColumn) Render ¶
func (c MJMLColumn) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLComponentName ¶
type MJMLComponentName = string
const ( MJMLTagName MJMLComponentName = "mjml" HeadTagName MJMLComponentName = "mj-head" BodyTagName MJMLComponentName = "mj-body" RawTagName MJMLComponentName = "mj-raw" // IncludeTagName is the include element. It is resolved before validation // and never reaches a component, so no component renders it - but it is // part of the language, and a custom component must not shadow it. IncludeTagName MJMLComponentName = "mj-include" // head specific AttributesTagName MJMLComponentName = "mj-attributes" BreakpointTagName MJMLComponentName = "mj-breakpoint" TextTagName MJMLComponentName = "mj-text" ClassTagName MJMLComponentName = "mj-class" AllTagName MJMLComponentName = "mj-all" FontTagName MJMLComponentName = "mj-font" TitleTagName MJMLComponentName = "mj-title" PreviewTagName MJMLComponentName = "mj-preview" StyleTagName MJMLComponentName = "mj-style" HTMLAttributesTagName MJMLComponentName = "mj-html-attributes" SelectorTagName MJMLComponentName = "mj-selector" HTMLAttributeTagName MJMLComponentName = "mj-html-attribute" SectionTagName MJMLComponentName = "mj-section" ColumnTagName MJMLComponentName = "mj-column" WrapperTagName MJMLComponentName = "mj-wrapper" GroupTagName MJMLComponentName = "mj-group" SpacerTagName MJMLComponentName = "mj-spacer" ImageTagName MJMLComponentName = "mj-image" SocialTagName MJMLComponentName = "mj-social" SocialElementTagName MJMLComponentName = "mj-social-element" DividerTagName MJMLComponentName = "mj-divider" TableTagName MJMLComponentName = "mj-table" ButtonTagName MJMLComponentName = "mj-button" HeroTagName MJMLComponentName = "mj-hero" AccordionTagName MJMLComponentName = "mj-accordion" AccordionElementTagName MJMLComponentName = "mj-accordion-element" AccordionTitleTagName MJMLComponentName = "mj-accordion-title" AccordionTextTagName MJMLComponentName = "mj-accordion-text" CarouselTagName MJMLComponentName = "mj-carousel" CarouselImageTagName MJMLComponentName = "mj-carousel-image" )
type MJMLDivider ¶
type MJMLDivider struct{}
func (MJMLDivider) AllowedAttributes ¶
func (d MJMLDivider) AllowedAttributes() map[string]AttributeValidator
func (MJMLDivider) DefaultAttributes ¶
func (d MJMLDivider) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLDivider) Name ¶
func (d MJMLDivider) Name() string
func (MJMLDivider) Render ¶
func (d MJMLDivider) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLGroup ¶
type MJMLGroup struct{}
func (MJMLGroup) AllowedAttributes ¶
func (g MJMLGroup) AllowedAttributes() map[string]AttributeValidator
func (MJMLGroup) DefaultAttributes ¶
func (g MJMLGroup) DefaultAttributes(ctx *RenderContext) map[string]string
type MJMLHead ¶
type MJMLHead struct{}
func (MJMLHead) AllowedAttributes ¶
func (h MJMLHead) AllowedAttributes() map[string]AttributeValidator
func (MJMLHead) DefaultAttributes ¶
func (h MJMLHead) DefaultAttributes(_ *RenderContext) map[string]string
type MJMLHero ¶
type MJMLHero struct{}
func (MJMLHero) AllowedAttributes ¶
func (h MJMLHero) AllowedAttributes() map[string]AttributeValidator
func (MJMLHero) DefaultAttributes ¶
func (h MJMLHero) DefaultAttributes(ctx *RenderContext) map[string]string
type MJMLImage ¶
type MJMLImage struct{}
func (MJMLImage) AllowedAttributes ¶
func (i MJMLImage) AllowedAttributes() map[string]AttributeValidator
func (MJMLImage) DefaultAttributes ¶
func (i MJMLImage) DefaultAttributes(_ *RenderContext) map[string]string
type MJMLNavbar ¶
type MJMLNavbar struct{}
MJMLNavbar renders mj-navbar. The markup follows mjml-navbar 5.4.1 (node_modules/mjml-navbar/lib/Navbar.js) including its hamburger checkbox, the Outlook-only link table and the component head style with the mobile menu rules.
func (MJMLNavbar) AllowedAttributes ¶
func (n MJMLNavbar) AllowedAttributes() map[string]AttributeValidator
func (MJMLNavbar) DefaultAttributes ¶
func (n MJMLNavbar) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLNavbar) Name ¶
func (n MJMLNavbar) Name() string
func (MJMLNavbar) Render ¶
func (n MJMLNavbar) Render(ctx *RenderContext, w io.Writer, node *node.Node) error
type MJMLNavbarLink ¶
type MJMLNavbarLink struct{}
MJMLNavbarLink renders mj-navbar-link. Its content is raw HTML (the parser streams it as a single string).
func (MJMLNavbarLink) AllowedAttributes ¶
func (l MJMLNavbarLink) AllowedAttributes() map[string]AttributeValidator
func (MJMLNavbarLink) DefaultAttributes ¶
func (l MJMLNavbarLink) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLNavbarLink) Name ¶
func (l MJMLNavbarLink) Name() string
func (MJMLNavbarLink) Render ¶
func (l MJMLNavbarLink) Render(ctx *RenderContext, w io.Writer, node *node.Node) error
type MJMLRaw ¶
type MJMLRaw struct{}
func (MJMLRaw) AllowedAttributes ¶
func (r MJMLRaw) AllowedAttributes() map[string]AttributeValidator
func (MJMLRaw) DefaultAttributes ¶
func (r MJMLRaw) DefaultAttributes(_ *RenderContext) map[string]string
type MJMLSection ¶
type MJMLSection struct {
IsWrapper bool
}
func (MJMLSection) AllowedAttributes ¶
func (s MJMLSection) AllowedAttributes() map[string]AttributeValidator
func (MJMLSection) DefaultAttributes ¶
func (s MJMLSection) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLSection) Name ¶
func (s MJMLSection) Name() string
func (MJMLSection) Render ¶
func (s MJMLSection) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLSocial ¶
type MJMLSocial struct{}
func (MJMLSocial) AllowedAttributes ¶
func (s MJMLSocial) AllowedAttributes() map[string]AttributeValidator
func (MJMLSocial) DefaultAttributes ¶
func (s MJMLSocial) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLSocial) Name ¶
func (s MJMLSocial) Name() string
func (MJMLSocial) Render ¶
func (s MJMLSocial) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLSocialElement ¶
type MJMLSocialElement struct{}
func (MJMLSocialElement) AllowedAttributes ¶
func (s MJMLSocialElement) AllowedAttributes() map[string]AttributeValidator
func (MJMLSocialElement) DefaultAttributes ¶
func (s MJMLSocialElement) DefaultAttributes(_ *RenderContext) map[string]string
func (MJMLSocialElement) Name ¶
func (s MJMLSocialElement) Name() string
func (MJMLSocialElement) Render ¶
func (s MJMLSocialElement) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLSpacer ¶
type MJMLSpacer struct{}
func (MJMLSpacer) AllowedAttributes ¶
func (s MJMLSpacer) AllowedAttributes() map[string]AttributeValidator
func (MJMLSpacer) DefaultAttributes ¶
func (s MJMLSpacer) DefaultAttributes(ctx *RenderContext) map[string]string
func (MJMLSpacer) Name ¶
func (s MJMLSpacer) Name() string
func (MJMLSpacer) Render ¶
func (s MJMLSpacer) Render(ctx *RenderContext, w io.Writer, n *node.Node) error
type MJMLTable ¶
type MJMLTable struct{}
func (MJMLTable) AllowedAttributes ¶
func (t MJMLTable) AllowedAttributes() map[string]AttributeValidator
func (MJMLTable) DefaultAttributes ¶
func (t MJMLTable) DefaultAttributes(ctx *RenderContext) map[string]string
type MJMLText ¶
type MJMLText struct{}
func (MJMLText) AllowedAttributes ¶
func (t MJMLText) AllowedAttributes() map[string]AttributeValidator
func (MJMLText) DefaultAttributes ¶
func (t MJMLText) DefaultAttributes(ctx *RenderContext) map[string]string
type MediaQueryGroup ¶
type MediaQueryGroup struct {
// Classes are the generated class names, in first-registration order.
Classes []string
// Rules are the declarations, without the surrounding braces.
Rules []string
}
MediaQueryGroup is one rule inside the document's breakpoint media query, together with every generated class that wants it. MJML 5 groups classes that share a rule into one selector list - `.a, .b { ... }` - instead of repeating the rule once per class, so a document with three columns of one width emits one rule rather than three identical ones.
type RenderContext ¶
type RenderContext struct {
// InlineStyles holds the stylesheets the document asked to inline - every
// <mj-style inline> block - in document order. The renderer applies them to
// the finished HTML.
InlineStyles []Stylesheet
// Fonts maps a font family name to the URL it is imported from. It is seeded
// with the built-in web fonts unless FontsConfigured reports a caller-supplied
// registry; <mj-font> adds to it.
Fonts map[string]string
// FontOrder lists font families in emission order. Built-in and declared
// fonts keep their registration order, and a caller-supplied registry keeps
// the order it was given in. A context that supplies Fonts without an order
// gets ascending family-name order instead, so it still renders
// deterministically.
FontOrder []string
// FontsConfigured reports that Fonts was supplied by the caller and must
// not be extended with the built-in web fonts. Fonts declared by the
// document with <mj-font> are still added on top of it.
FontsConfigured bool
// BodyContent is the rendered body HTML, used to detect which registered
// web fonts the document actually uses.
BodyContent string
// CustomComponents holds the custom components the renderer was configured
// with, keyed by tag name. Validation and rendering look a tag up here after
// the built-in tables, so a registered tag is a first-class element.
//
// The map belongs to the renderer and every render of that renderer shares
// it, including concurrent ones: components must not modify it. A nil or
// empty map is a renderer without custom components.
CustomComponents map[string]Component
// AttributeDefaults holds per-tag defaults from <mj-attributes>, keyed by
// tag name. The <mj-all> defaults live under the "mj-all" key.
AttributeDefaults map[string]AttributeMap
// Classes holds the attributes of each <mj-class>, keyed by class name.
Classes map[string]AttributeMap
// ClassDefaults holds the per-tag defaults declared inside a <mj-class>,
// keyed by class name and then by tag name.
ClassDefaults map[string]map[string]AttributeMap
// HTMLAttributes holds the <mj-html-attributes> selectors in declaration
// order. Selectors with the same path are merged in place.
HTMLAttributes []HTMLAttributeSelector
// MJMLStylesheet maps a generated class name to the CSS rules components
// registered for it.
MJMLStylesheet map[string][]string
// MJMLStyleOrder lists those class names in first-registration order; the head
// emits them in this order, so the cascade is deterministic.
MJMLStyleOrder []string
// ComponentHeadStyles holds the named component-level <style> blocks (navbar,
// accordion, ...) in first-registration order. They are keyed by component
// name, so multiple instances of the same component register their style
// only once, like MJML's addHeadStyle.
ComponentHeadStyles []ComponentHeadStyle
// InstanceComponentHeadStyles holds component stylesheets that depend on the
// rendered instance rather than only on the breakpoint (mj-carousel, whose
// CSS embeds the carousel id and the number of images). MJML keeps these in
// an array without deduplication and emits them before ComponentHeadStyles.
InstanceComponentHeadStyles []ComponentHeadStyle
// Gutter is the mj-section gutter that applies to the columns below it:
// the space a section's columns keep between themselves. Empty when the
// section has none, which is MJML's own test for "no gutter".
Gutter string
// ContainerDirection is the direction of the section or group rendering the
// columns. Column gutter padding mirrors for rtl, so it needs the
// container's direction rather than the document's.
ContainerDirection string
// InGroup reports that the column being rendered sits inside an mj-group,
// which does not stack on mobile and therefore keeps desktop padding.
InGroup bool
// IDGenerator produces the opaque ids MJML assigns to components that need
// them (navbar hamburger labels, carousels). It is set once per render by
// the renderer, so a nil generator falls back to DefaultIDGenerator.
IDGenerator func() string
// IncludeMobileFullWidthStyle reports that the document contains an mj-image,
// which adds MJML's mobile-full-width rule to the head.
IncludeMobileFullWidthStyle bool
// ForceOWADesktop is set by <mjml owa="desktop"> and makes the generated
// conditional CSS target desktop Outlook.
ForceOWADesktop bool
// PrinterSupport repeats the generated media queries in an
// `@media only print` block, like MJML's printerSupport option.
PrinterSupport bool
// ContainerWidth is the width content may occupy at the current nesting
// depth, such as "600px". Containers narrow it for their children and restore
// it afterwards; the renderer seeds it from the body width.
ContainerWidth string
// PreviewText is the text of <mj-preview>, emitted as the hidden preheader of
// the body.
PreviewText string
// Title is the text of <mj-title>, used as the aria-label of the body div.
Title string
// Breakpoint is the document's media-query breakpoint, such as "480px".
// <mj-breakpoint> overrides the default.
Breakpoint string
// Language is the document language from <mjml lang>, emitted as the lang
// attribute of the body.
Language string
// Direction is the document direction from <mjml dir>, emitted as the dir
// attribute of the body.
Direction string
// contains filtered or unexported fields
}
RenderContext is the state of one render: what the document's head configured, what the renderer passes down the component tree and what components accumulate for the head. The renderer creates one per document; every component in that document receives the same pointer.
The exported fields are frozen API: their meaning and their type do not change (see the package documentation). A component that narrows a field for its children - the container width, the contextual font family - restores it before it returns.
func (*RenderContext) AddComponentHeadStyle ¶
func (c *RenderContext) AddComponentHeadStyle(name string, style func(breakpoint string) string)
AddComponentHeadStyle contributes a named stylesheet to the document head, rendered with the document breakpoint. It is the mechanism the built-in navbar, accordion and image components use. The block is keyed by name: a component registering the same name again - its second instance, for example - replaces the previous block and keeps its position, so the head carries one deterministic block per component.
func (*RenderContext) AddFluidOnMobileClass ¶
func (c *RenderContext) AddFluidOnMobileClass(className string)
AddFluidOnMobileClass makes the head emit MJML's fluid-on-mobile rule for className: inside the media query below the breakpoint, `table.<className>` gets width:100% !important and `td.<className>` width:auto !important. It is the rule mj-image's fluid-on-mobile attribute uses, exposed so a custom component can opt its own class in. Classes are emitted in first-registration order, deduplicated, and after mj-image's own class when the document has one; an empty class name is ignored.
func (*RenderContext) AddInstanceComponentHeadStyle ¶
func (c *RenderContext) AddInstanceComponentHeadStyle(name string, style func(breakpoint string) string)
AddInstanceComponentHeadStyle contributes a stylesheet specific to one rendered instance - CSS that embeds an id or a count, as mj-carousel's does - and so must not be merged with another instance's block. Blocks are emitted in registration order, before the named component styles, and are never de-duplicated: two instances contribute two blocks.
func (*RenderContext) AddMediaQuery ¶
func (c *RenderContext) AddMediaQuery(className string, declarations []string)
AddMediaQuery contributes className to the document's breakpoint media query. It is the mechanism the built-in columns and groups use for their width classes: the rules are emitted inside `@media only screen and (min-width: <breakpoint>)` for className, and repeated in the Thunderbird, print and desktop-Outlook variants MJML generates. A class keeps its first-registration position; registering it again replaces its rules, so two instances of one component contribute a single class block.
func (RenderContext) MediaQueryGroups ¶
func (c RenderContext) MediaQueryGroups() []MediaQueryGroup
MediaQueryGroups returns the generated class rules grouped by identical declarations. Groups keep the position of the first class that wanted the rule, which is the order MJML 5 emits them in.
type Rule ¶
type Rule struct {
Selectors string `json:"selectors"`
Declarations []Style `json:"declarations"`
// contains filtered or unexported fields
}
Rule represents a standard CSS rule with selectors and declarations.
func (*Rule) CompileSelectors ¶
func (r *Rule) CompileSelectors()
CompileSelectors compiles the rule's selector list and caches the result. The stylesheet builders call it once, when the stylesheet is constructed, so rendering never parses selectors.
func (*Rule) CompiledSelectors ¶
CompiledSelectors returns the rule's compiled selector list and reports whether the rule is usable. A rule whose selectors do not compile reports false and must be skipped. Rules that were never compiled - stylesheets built by hand rather than by the head parser - are compiled on first use.
type Style ¶
type Style struct {
Property string `json:"property"`
Value string `json:"value"`
Important bool `json:"important"`
}
Style represents a single CSS property-value pair.
type Stylesheet ¶
Stylesheet is the top-level structure for our parsed CSS.
Source Files
¶
- component.go
- conditional_tag.go
- context.go
- csssanitize.go
- custom.go
- doc.go
- error.go
- fonts.go
- mjml.go
- mjml_accordion.go
- mjml_body.go
- mjml_button.go
- mjml_carousel.go
- mjml_carousel_image.go
- mjml_column.go
- mjml_divider.go
- mjml_group.go
- mjml_head.go
- mjml_hero.go
- mjml_image.go
- mjml_navbar.go
- mjml_raw.go
- mjml_section.go
- mjml_social.go
- mjml_social_element.go
- mjml_spacer.go
- mjml_table.go
- mjml_text.go
- render_children.go
- templates.go
- types.go
- util.go
- validate.go