DEV Community

Cover image for I said my MJML i18n library would never have loops. Then we needed a list.
Michal Král
Michal Král

Posted on AI-assisted

I said my MJML i18n library would never have loops. Then we needed a list.

Back in May I wrote about @checkthiscloud/mjml-i18n, a tiny MJML preprocessor that gives your email templates exactly two things: variables and co-located translations. I was pretty proud of what it didn't do:

No loops, no conditionals, no arbitrary expressions, no eval. […] That constraint is the whole point.

Version 0.1 adds loops and conditionals.

So yeah — we changed our mind. Here's why, and where the line still holds.

What broke the rule: a daily digest

The two-tiny-things model is perfect for transactional email: "Hi {name}, here's your link." One template, a handful of values, done.

Then we needed a daily digest. You know the shape:

  • a headline with today's count — or a calm "nothing urgent" message when there's nothing,
  • one row per item, each with a link and an optional note,
  • a schedule grouped by day, with a nested list of events under each day.

None of that is two tiny things. It's a list, an empty state, an optional field and a list inside a list.

Without loops in the template, you have exactly two options, and both are bad:

  1. Build the HTML in code and pass it in as a variable. Now your markup lives in a JS string, outside MJML, and you've lost the whole reason you're using MJML.
  2. Go back to running a full template engine before MJML. Which is literally the thing this library exists to avoid.

We stopped pretending a list was an edge case.

What it looks like now

Same {{ … }} markers, a few new statement shapes:

<mjml>
  <i18n type="json">
    {
      "en": { "title": "Today: {count} items", "calm": "Nothing urgent", "guests": "{count} guests", "open": "Open" },
      "cs": { "title": "Počet úkolů dnes: {count}", "calm": "Nic nehoří", "guests": "{count} hostů", "open": "Otevřít" }
    }
  </i18n>
  <mj-body>
    <mj-section><mj-column>
      {{ if items }}
      <mj-text>{{ i18n('title', { count: get('itemCount') }) }}</mj-text>
      {{ else }}
      <mj-text>{{ i18n('calm') }}</mj-text>
      {{ endif }}
    </mj-column></mj-section>

    {{ for item in items }}
    <mj-section><mj-column>
      <mj-text>{{ get('item.title') }}</mj-text>
      {{ if item.note }}<mj-text>{{ get('item.note') }}</mj-text>{{ endif }}
      <mj-button href="{{ get('item.url') }}">{{ i18n('open') }}</mj-button>
    </mj-column></mj-section>
    {{ endfor }}

    {{ for day in days }}
    <mj-section><mj-column>
      <mj-text>{{ get('day.label') }}</mj-text>
      <mj-table>
        {{ for event in day.events }}
        <tr><td>{{ get('event.name') }}</td><td>{{ i18n('guests', { count: get('event.guests') }) }}</td></tr>
        {{ endfor }}
      </mj-table>
    </mj-column></mj-section>
    {{ endfor }}
  </mj-body>
</mjml>
Enter fullscreen mode Exit fullscreen mode

Rendering hasn't changed:

import mjml from 'mjml';
import { createI18nPreprocessor } from '@checkthiscloud/mjml-i18n';

const preprocessor = createI18nPreprocessor({
  locale: 'cs',
  vars: {
    itemCount: 2,
    items: [
      { title: 'Approve the reminder', note: 'Due at 9:00', url: 'https://example.com/a' },
      { title: 'Check the domain', note: null, url: 'https://example.com/b' },
    ],
    days: [
      { label: 'Saturday', events: [{ name: 'Fair', guests: 1900 }, { name: 'Ball', guests: 820 }] },
      { label: 'Sunday', events: [{ name: 'Run', guests: 2400 }] },
    ],
  },
});

const { html } = await mjml(template, { preprocessors: [preprocessor] });
Enter fullscreen mode Exit fullscreen mode

The loop variable (item, day, event) works everywhere you'd expect it to: in get(), inside i18n() params and in nested blocks. Because the blocks are resolved on the raw XML before MJML parses it, a for can repeat a whole <mj-section> or just a <tr> inside an <mj-table> — MJML only ever sees the finished markup.

Where we kept the line

The new syntax is the smallest thing that makes the digest work. There is no expression language:

  • Conditions take a path, never an expression. {{ if item.note }} is fine. {{ if a && b }}, {{ if count > 0 }} and {{ if(a) }} are not statements at all — they get left in the output untouched, like any other marker the library doesn't recognize.
  • Want a comparison? Compute it in your data. Pass order.isLate, not order.dueAt < now. That logic belongs in code you can test, not in an email template.
  • Truthiness is boring on purpose. false, null, undefined, '', 0, NaN and an empty list are false; everything else is true. An empty list being false is what makes {{ if items }} … {{ else }} … {{ endif }} work as an empty state.
  • A loop variable owns its name. Inside {{ for item in items }}, a typo like get('item.titel') reports Missing variable: item.titel. It doesn't quietly fall through to some global called item.
  • Still no eval. The only statement shapes are for <name> in <path>, endfor, if <path>, else and endif; everything else goes through the same tiny allowlist evaluator as before.

So it's still not a template engine. It's loops and ifs over data you've already prepared.

The breaking change: get() now escapes

Once you loop over a list of things users typed in — titles, notes, names — you're putting user data into HTML and into attributes. So in 0.1, values read by get() are HTML-escaped: &, <, >, " and ' become entities.

<mj-text>{{ get('comment') }}</mj-text>
<!-- "<b>hi</b>" now prints as text, not as bold -->
Enter fullscreen mode Exit fullscreen mode

Translations are part of your template, so their markup is kept. A get() value handed into i18n() params is escaped, so a translation like "Welcome <strong>{name}</strong>" keeps its <strong> but can't be broken by a name like Tom & <Jerry>.

If you were deliberately passing markup through vars, that's the part that changes for you. (And honestly: you shouldn't have been.)

One honest note: 0.1.0 printed Date objects as [object Object]. We missed that the deep escaping walked every object, including the ones that have their own string form. 0.1.1 fixes it — Dates, URLs and class instances print through String() again, escaped. Use 0.1.1 or newer.

Mistakes stay loud, not fatal

Same philosophy as before: nothing throws into your render. A broken template prints its problem right where it happened, so you see it in the preview instead of the render blowing up:

You wrote You get
{{ for x in missing }} Missing variable: missing
{{ for x in title }} (a string) Not a list: title
an endfor with nothing to close Unexpected endfor
a for you forgot to close Unclosed block: for item in items

That's great in a preview, less great when it lands in a customer's inbox.

What's still missing

Look at the Czech translation above: "{count} hostů". That's correct for 1900 guests. For 2 guests, Czech says 2 hosté; for 1, 1 host. Params are still plain {name} substitution, so plurals are on you for now. ICU message format is on the roadmap, and the formatting layer is already a swap-in seam, so it can land without touching the marker syntax.

Try it

It's 0.x, MIT, built for MJML v5.

npm install @checkthiscloud/mjml-i18n@^0.1.1 mjml
Enter fullscreen mode Exit fullscreen mode

In May I said the constraint was the whole point. I still think it is — we just moved it. The rule used to be "no logic in templates". Now it's "no expressions in templates". That turned out to be the line that actually matters.

Top comments (0)