Last year, our colleague Hugo Giraudel wrote a blog post about integrating MJML into Rails. After working with it for a while in some of our other projects and with the recent upgrade of the language to version 3, we thought that it’s time for an update!
Use MJML in a Rails Email Layout Setup
If you have different kinds of emails in your project, you might want to extract some of the shared logic into something you could reuse (“Don’t Repeat Yourself!”). In Rails this is done through the Action Mailer Layouts. To do this you have to create a layout file and use yield
to render your partial inside the layout:
Now you can add this layout to your mailer class:
All you have to do now is to remove the shared markups from your partial:
Pay attention to the different file formats (when and where to use .mjml
or .mjml.erb
), otherwise it won’t work!
Style Your MJML Templates
Creating email templates for the same project also means applying similar stylings to each of the templates. With the recent upgrade of MJML to version 3 it became a lot easier to reuse some of the stylings.
Within the mj-attributes
tag you can now define global stylings with mj-all
; create styling classes with mj-class
; or set the styling for a specific tag by just mentioning it:
Another way to apply styling is to use mj-style
and write plain CSS in it. You can then use mj-raw
to write plain html and apply the CSS class:
Use Web Fonts
There are several ways of integrating web fonts into your emails. Campaign Monitor has a good introduction on that. MJML introduced the mj-font
tag to allow customized fonts, which should be sufficient in most of the cases:
But in one of our projects, we are loading fonts which are nested in the Rails assets folder structure ./app/assets/fonts/*
and we used to load it with @font-face
into our email templates.
To allow this again we had to hack MJML a bit, since we weren’t able to find anything else to replace this.
Wrapping Up
We are still very happy with MJML and are trying to integrate it into more and more of our projects.
The version 3 upgrade helps a lot in terms of DRY up the code and to integrate standard styling elements. But when the design becomes more complex, we did reach some of the limits of MJML. But the lively discussions and issue requests online promise that new features are soon to come.
We’ve been testing our emails with Litmus, a service which allows us to see how our emails get rendered on different devices with different email clients. Since the switch to MJML we’ve more or less stopped experiencing broken stylings or missing elements. 🤘
PS.: the official list of MJML packages also has been a great source of help.