Use MJML to pregenerate your emails, then Handlebars with i18n support to generate your final emails (html and text).
BONUS: Live preview your templates with sample variables for all your languages.
npm install mjml-handlebars
yarn add mjml-handlebars
Add this scripts to your package.json
"emails": "mjml-handlebars",
Use this if you are using custom root folder and dotenv
"emails": "node -r dotenv/config node_modules/.bin/mjml-handlebars",
npm install -D npm-run-all @compodoc/live-server nodemon
yarn add -D npm-run-all @compodoc/live-server nodemon
Additional package.json scripts:
"emails:dev": "run-p emails:watch emails:preview",
"emails:watch": "nodemon --exec 'npm run emails' -e mjml -i emails/output",
"emails:preview": "live-server -q emails/preview"
Add emails/preview
to your .gitignore
Generate an emails/templates
folder, add your mjml templates there. If your run the emails
script, the emails/output and emails/preview folders will be generated with the compiled assets.
By default it uses {cwd}/emails
as root folder, can be changed with MJML_HANDLEBARS_ROOT
environment variable.
Run
emails:dev
to watch for changes and a live server preview
To generate the final email, the precompiled version of the handlebars email will be used to improve performance. Example:
import { generateEmail } from 'mjml-handlebars'
const { html, text, subject } = generateEmail(
'welcome',
{
email: 'john@gmail.com',
items: [{ name: 'item1' }, { name: 'item2' }, { name: 'item3' }],
showButton: true,
disclaimer: 'This is the disclaimer',
},
'de', // Language
'en' // Optional fallback Language
)
There are 4 required comment blocks (only available for main templates, not partials):
- text (plain text): contains the email in text mode (with same handlebars support as the mjml part)
- subject (plain text): contains the email subject (with same handlebars support as the mjml part)
- i18n (YAML): languages and messages for translations
- vars (YAML): sample variables for previewing
There is support for logical operators, taken from here
Example template:
See a working example project at /example
.
MIT