Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

22.2 KB
Raw Blame

Liquid and MJML Email Templates

Status: In Review — the whole plan is built on feat/emails-liquid (spree/spree#14772) Target: Spree 6.0 (moved from 6.1 on 2026-09-29) Depends on: v3 serializers (spree_api), spree_emails (5.6 rebuild) Author: Damian Legawiec Last updated: 2026-09-30 Tracking: Linear V-3720 · GitHub spree/spree#14755

Summary

Transactional emails are the last HTML Spree renders through Rails views. This plan replaces all 61 ActionMailer ERB templates (16 mailers across spree_core and spree_emails) with Liquid templates written in MJML. Liquid fills in the data first, then MJML turns the result into email-safe HTML, using the mrml gem (a Rust port of MJML) with no Node involved. Templates read plain JSON produced by serializers, never models. This makes the templates:

  • Portable. Liquid also runs in Node through liquidjs.
  • Safe to hand to merchants. Liquid is built for untrusted templates.
  • Much shorter than the hand-written HTML tables they replace.

Three things are out of scope and come later on this foundation: merchant editing in the dashboard, templates stored in the database, and live previews. Action Mailer still delivers every email.

Key Decisions (do not deviate without discussion)

  • Liquid for data, MJML for layout (2026-09-24).

    • Why Liquid: it's the only template language with maintained, first-class engines in both Ruby (liquid) and TypeScript (liquidjs). That matches the long-term direction of shrinking Rails in the stack. It was also designed for untrusted, merchant-written templates. Handlebars, the other common choice for email templates, has only a weak Ruby port and a history of code-execution vulnerabilities when compiling templates from outside sources.
    • Why MJML: it's the most widely used email layout language. A dozen layout tags (mj-section, mj-column, mj-button) compile to the nested tables, inline styles and Outlook workarounds that email clients need, and mobile stacking comes built in.
    • Rejected: React Email, Maizzle (now Vue with Tailwind) and other Tailwind-for-email tools. They are build-time tools on Node, so the file an author writes is not the file that runs. Merchant editing would need Node on the server, or would expose unreadable compiled output.
    • Rejected: React Email's visual editor. Templates must be managed as code.
    • Rejected: plain HTML tables with Liquid. Nothing new to learn, but Spree would keep maintaining the fragile table markup by hand.
  • Liquid renders first, then MJML, on every email (2026-09-24). Loops and conditions can then sit anywhere between MJML tags without <mj-raw> wrappers, and partials pulled in by {% render %} compile together with the template. Measured with mrml, MJML takes about 0.6 milliseconds per email and Liquid about 1.4 milliseconds, so there's nothing to cache.

  • Every output is escaped unless marked safe (2026-09-24). Liquid doesn't escape HTML by default. A customer named <a href="https://evil.test">Click to verify</a> renders a live link, including into the store owner's new-order notification. Every value a template prints is HTML-escaped, which was verified to neutralize that input. Values known to be safe HTML opt out explicitly with a raw filter. Escaping before MJML also stops customer data from forming MJML tags.

    • Escaping happens where output is written, not through Liquid's global_filter (2026-09-29, found while building). {% assign %} runs through the global filter too, so a value was escaped once when assigned and again when printed, and assigned numbers and lists became strings. Spree instead extends Liquid's variable output, active only inside an email render.
    • Partials inherit escaping and strict mode (2026-09-29, found while building). {% render %} gives a partial a fresh context that Liquid does not carry these settings into, so without Spree's context subclass everything a partial printed skipped escaping. A partial may leave an argument out (it reads as empty); a misspelled field still raises.
  • Templates keep Rails view paths (2026-09-25). A template sits where its ERB sat, with the extension changed: app/views/spree/order_mailer/confirm_email.liquid. That path is also the template's key, so a later database row or Node renderer addresses it as spree/order_mailer/confirm_email. The upgrade note is a list of renames, and Rails developers already know where to look.

    • Accepted trade-off: template names are tied to Ruby mailer classes and methods for good. A future Node renderer keeps these paths rather than getting cleaner names, and renaming a mailer or one of its methods becomes a breaking change for every app that overrides that email.
  • Templates read serializer output, never models (2026-09-25). Liquid "drops" that wrap models aren't used.

    • Customer emails receive hashes from a new family of email serializers, each inheriting from the public v3 Store serializer, for example Spree::Emails::OrderSerializer < Spree::Api::V3::OrderSerializer. They add only what emails need. The audit found real gaps in the Store serializers: SKU, product link, per-line amount before discounts, the promotion/manual discount split, the order-group purchase breakdown, and fulfillment items as more than ids. Filling those gaps here keeps the public Store API, SDK types and webhook payloads unchanged.
    • Accepted trade-off: a third serializer family to maintain. Email data is a superset of the webhook payload for the same record, not identical to it.
  • Alba moves into spree_core (2026-09-25). Core's back-office emails (admin and seller password resets, invitations, import and export finished, webhook disabled) must work in every installation, including those without spree_api, as the marketplace plan requires. With Alba in core, they use email serializers too, so every email takes its data one way.

    • What moves: spree_core gains the alba dependency. The Alba setup in spree/api/config/initializers/alba.rb (backend, inflector, the iso8601 type) moves into core, so both gems configure Alba once and identically.
    • Where serializers live: core's email serializers are in spree/core/app/serializers/spree/emails/ and stand alone, because the v3 Admin serializers live in spree_api. That makes each field explicit. The Admin webhook-endpoint serializer, for example, carries secret_key, which an email must never render.
  • Tokens never come from a serializer. Password-reset, invitation, newsletter, download and payment-link URLs carry secrets. The mailer builds them and passes them as email-specific values. Email serializers never expose a token.

  • Action Mailer stays the delivery layer. Mailers keep choosing the recipient, locale, from and reply_to, keep their guards (for example CompanyMailer cancels delivery for a non-pending invitation, and SellerMailer cancels when there are no recipients), and keep delivering through the job queue with retries. Only rendering changes.

  • The template lookup is a chain, with room for a database step. The renderer asks a resolver for a key. In this plan the resolver checks the host app's Liquid file, then the gem's Liquid default. The later editing work adds a store-scoped database step in front without changing any mailer.

  • The plain-text part is generated from the HTML (2026-09-25). Spree converts the final HTML to text, keeping links as label (url). A confirm_email.text.liquid next to the template overrides it. This halves the file count, and the text can never drift from the HTML.

    • Accepted trade-off: generated text is a little less tidy than hand-written text. Seven emails that have no text part today gain one.
  • Copy keeps its translation keys through a t filter (2026-09-25). Default templates read the existing Spree.t keys, for example {{ 'order_mailer.confirm_email.instructions' | t }}. One template serves every language, and no locale files move. A merchant editing later can still type plain text for a single-language store.

    • Accepted trade-off: default templates read less naturally than plain copy.
  • No image_url filter (2026-09-29, changed while building). A resized variant is built from the stored file, which a template holding only a URL cannot reach; serializers ship the URL of the size an email shows instead.

  • Emails with no gap use the Store serializer as it is (2026-09-29). Customer, seller and company emails read Spree.api.customer_serializer, seller_serializer and company_serializer directly, so a host app's replacement serializer applies to its emails too. Only order, order group, fulfillment and return get email serializers.

  • Filters are a small, deliberate public interface, with the most widely used Liquid filter names where the meaning matches. Agents and developers reach for those names first. Matching names where the behavior matches (money, money_with_currency, date, t) turns that habit into correct code. Nothing is added just because a Rails helper existed.

  • The subject lives in the template. Each template carries its subject line as Liquid, so one email is one self-contained unit. That's the shape a database row takes later.

  • All 16 mailers migrate in 6.0 (2026-09-25, moved from 6.1 on 2026-09-29). The plan was pulled into 6.0 so the release ships one email stack rather than changing it again one release later, and so merchant editing can start on 6.x without a template migration in between.

  • ERB overrides of Spree's emails are dropped in 6.0, with no bridge (2026-09-29, replacing an earlier same-day decision to keep them in a spree_legacy_emails gem for one release). 6.0 is a major release that already breaks larger things, the ERB emails were only rebuilt in 5.6, and a bridge would have cost a gem, a CI lane, an ERB step in the lookup and a 6.1 cleanup. An app's ERB override of a Spree email is not rendered, and the default design goes out instead.

    • Accepted trade-off (2026-09-30): there is no warning. A boot-time check listing ignored ERB overrides was built and then removed: it ran on every boot of every app, forever, to catch a one-time upgrade problem the upgrade guide already covers.
  • Custom mailers keep working unchanged (2026-09-29). A mailer that inherits Spree::BaseMailer and renders its own ERB views with mail still gets Spree's layout: core keeps a one-line layouts/spree/base_mailer.html.erb that wraps the rendered view in the Liquid layout, so custom emails carry the new header and footer. The spree/shared/_mailer_hero and _mailer_button ERB partials stay in core, restyled, because custom views commonly use them. Only overrides of Spree's own emails need porting.

  • The subject is front matter (2026-09-29). A template opens with a small YAML block holding its subject as Liquid, the Jekyll convention:

    ---
    subject: "{{ store.name }} {{ 'order_mailer.confirm_email.subject' | t }} #{{ order.number }}"
    ---
    

    The block maps one-to-one onto a subject column when templates move to the database. Rejected: a {% subject %} tag in the body, which would have to be dug back out of the body for that move.

Design Details

Rendering pipeline

mailer ── key + data ──▶ Spree::Emails::Renderer            (spree_core)
                           │
                           ├─ 1. resolve key                 host .liquid → gem .liquid
                           ├─ 2. Liquid: subject + body      escaped output, strict variables, render limits
                           │      body = layout wrapping the template through {{ content_for_layout }}
                           ├─ 3. MJML → HTML                 mrml
                           └─ 4. text part                   .text.liquid override, or generated from the HTML
                           ▼
mail(subject:, html:, text:)  ── Action Mailer delivery (unchanged)
  • Dependencies in spree_core:
    • liquid: pure Ruby.
    • mrml: MIT licensed, with precompiled binaries for Linux (glibc and musl, x86_64 and arm64), macOS and Windows, so Docker builds need no Rust toolchain. mrml is a single-maintainer binding; if it's abandoned, the fallback is compiling MJML through mjml on Node in a separate step, with no change to templates.
    • alba.
  • The layout is app/views/layouts/spree/base_mailer.liquid: <mjml>, <mj-head> (fonts and default attributes through <mj-attributes>), the header with the store logo, the footer, and {{ content_for_layout }} where the body goes. content_for_layout is the conventional Liquid name for the same idea. MJML's default Google Fonts import is replaced with the stack the current ERB stylesheet uses.
  • Partials are loaded with {% render 'spree/shared/line_item', item: item %} and resolve to app/views/spree/shared/_line_item.liquid, the Rails partial naming. render gives each partial its own isolated variables. The ERB layout tricks that don't exist in Liquid are replaced:
    • _mailer_hero used as a layout with yield becomes named MJML styles (mj-class="heading", greeting, lead, note) that templates use directly; _mailer_button is plain <mj-button>.
    • content_for :head styles move into the layout's <mj-head>.
  • Resource limits. Liquid's render limits are set so a runaway loop fails one email instead of stalling the job queue. Strict variables make an unknown variable raise in development and test, so a typo like order.nubmer fails a spec rather than rendering blank.

Data each template receives

Variable Source
The record (order, order_group, fulfillment, return, customer, seller, company, …) Its email serializer as a hash. Customer emails: spree_emails serializers inheriting the v3 Store ones. Back-office emails: core serializers.
store Name, storefront URL, absolute logo URL (mailer logo, falling back to the store logo), support email, address, default currency and locale. One core serializer; no Store API serializer exists for stores today.
Email-specific values Built by the mailer: reset, invitation, confirmation, download and payment-link URLs with their tokens; the resend flag.

Template audit (2026-09-25)

What each email's templates read today, and the gaps its serializer has to close. "Store" means the public v3 Store serializer.

Mailer Audience Gaps its email serializer closes
OrderMailer (confirm, cancel, store-owner notification, payment link) customer; store staff Order: customer name (billing, then shipping, then email fallback, today's name_for), display_total_minus_store_credits, discounts split into promotion and manual with label, delivery totals grouped by rate name. Line item: sku, display_amount (price × quantity before discounts, not display_total), product storefront URL, image URL.
OrderGroupMailer (confirm, store-owner notification) customer; store staff Almost everything: customer name, PO number, line items, fulfillment groups (seller names, items with quantities and amounts, name, cost), unfulfilled items, every totals field, discounts, fees. The view currently queries the database and multiplies amounts itself; both move into the serializer.
FulfillmentMailer (ShipmentMailer forwards to it) customer The order it belongs to; delivery method name; manifest items with line-item data (today they're ids only); tracking URL.
ReturnMailer (refunded) customer display_refunded_total (Store's display_refund_total is a different figure); returned line items with name, SKU and options.
DigitalAssetMailer (files ready) customer Absolute download URLs (the serializer has relative paths), built by the mailer since they carry tokens.
CustomerMailer (password reset, data export) customer Nothing; the URLs and expiry come from the mailer.
NewsletterMailer (confirmation) subscriber Nothing; the confirmation URL comes from the mailer.
CompanyMailer (invitation) buyer Company name exists; the accept URL comes from the mailer.
SellerMailer (approved, suspended, rejected) seller Seller name exists; the dashboard URL comes from the mailer.
AdminUserMailer, SellerUserMailer (password reset) staff; seller user Nothing; locale is the store's admin locale, as today.
InvitationMailer (invitation, accepted) invitee; inviter Resource name, inviter and invitee names (none are serialized today); accept URL from the mailer.
ExportMailer, ImportMailer (done) staff User first name, file name, completed and failed row counts, results URL.
WebhookMailer (endpoint disabled) staff Name, URL, disabled reason and date. Never secret_key.

Helpers replaced by filters or serializer fields:

  • name_for, spree_storefront_resource_url, fulfillment_tracking_link_to and digital_link_download_url become serializer fields or mailer-built values.
  • Spree::Money and the display_* methods become money or preformatted display_* fields.
  • I18n.l and strftime become date.
  • The image helpers become serializer fields carrying the thumbnail's URL (item.image_url, store.logo_url).
  • Spree.t becomes t.

Filters

Filter Example Notes
money / money_with_currency {{ line_item.amount | money }} Conventional Liquid names; formatted through Spree::Money in the email's currency
date {{ order.completed_at | date: 'long' }} In the store's time zone, never the server's
t {{ 'order_mailer.confirm_email.dear_customer' | t: name: order.customer_name }} Existing Spree.t keys with interpolation
raw {{ product.description_html | raw }} Opts out of escaping; only for HTML sanitized on write

Previews and tests

  • The bundled Action Mailer previews (/rails/mailers) keep working, because they call the mailers.
  • A shared spec renders every shipped template with factory data under strict variables, so a missing or misspelled variable fails CI.
  • Every rendered email is checked for leftover {{, {% and <mj-, which catches both an unrendered Liquid tag and an MJML tag that didn't compile.
  • An escaping spec renders each customer-facing email with an HTML payload in every free-text field (names, addresses, notes, company names).

Documentation

  • A developer guide in docs/developer/ on overriding an email: where files go, the layout and partials, filters, escaping, and the plain-text override.
  • A reference of the variables of every customer email, maintained by hand in docs/developer/customization/email-variables.mdx and published through llms.txt too. Agents otherwise guess variable names they have seen on other platforms, and this reference corrects that.
  • A 6.0 upgrade note listing every ERB path with its Liquid replacement.

Migration Path

  1. Alba into core. Add the dependency, and move the Alba setup from spree_api into core.
  2. Renderer and resolver in spree_core: liquid and mrml, the lookup chain, escaping, limits, filters, and text generation.
  3. Layout and partials in MJML, matching the current ERB design visually.
  4. Core mailers (admin user, seller user, invitation, import, export, webhook), each with its core email serializer and render spec. One mailer per commit.
  5. spree_emails mailers (order, order group, fulfillment and shipment, return, digital asset, customer, newsletter, company, seller), each with its email serializer and render spec. One mailer per commit.
  6. Docs: the override guide, the variable reference for customer emails, and the upgrade note.

Constraints on Current Work

  • Keep email views dumb. New emails and changes to existing ones compute values in the mailer, or expose them from a serializer, rather than calling model methods or new helpers from the view. Every model call in a view today is migration work for this plan, and the order-group views that query the database are the worst case.
  • Don't add new mailer view helpers.
  • Don't widen the public Store serializers for an email's sake. A field only an email needs goes on the email serializer once this plan lands.
  • Renaming a mailer class or method is a breaking change once templates are Liquid, because the view path is the template key that apps override (and, later, that database rows reference).
  • Never put a token in a serializer. URLs carrying secrets are built by the mailer.
  • New mailers (message relay, gift cards) may still ship in ERB before this plan lands, but should follow these rules so their conversion is mechanical.

Open Questions

None block 6.0. Merchant editing is designed in 6.0-email-template-editor.md; the items below were its starting brief:

  • Editing in the dashboard, database-stored templates as a store-scoped step in front of the resolver, and revision history.
  • Preview renders on the server (decided 2026-09-30): the dashboard sends a draft template to an Admin API endpoint, and the same Ruby renderer fills it with sample data and returns the HTML. What the merchant sees is exactly what customers receive, there is one renderer to maintain, and a send-test-email action is a small addition. Rendering in the browser through liquidjs and MJML's browser build stays an option for later, if typing responsiveness demands it; it would mean keeping Spree's filters in step in two languages.
  • Store branding settings (colors, fonts) feeding the layout's <mj-attributes>. Today the only branding is the logo and mailer logo.
  • Warning merchants when a default they customized has changed, with a diff.

Each is unblocked by this plan shipping: the resolver chain, the email keys and the data contract are what the editor builds on.

References

  • 6.0-multi-vendor-marketplace.md: back-office emails stay in core; seller mailers; the order-group confirmation
  • 6.0-digital-assets.md: DigitalAssetMailer
  • 6.0-seller-onboarding-requirements.md: new SellerMailer emails
  • 6.0-email-template-editor.md: merchant editing in the dashboard, built on this plan
  • 6.1-marketplace-message-relay.md: MessageMailer (new mailer)
  • 6.0-6.1-loyalty-gift-cards-store-credits.md: gift card mailer (new mailer)
  • Liquid: https://shopify.github.io/liquid/ · liquidjs: https://liquidjs.com · MJML: https://mjml.io · mrml gem: https://github.com/hardpixel/mrml-ruby