4

I am in the process of converting some legacy email templates to mjml (using mjml version 4.2). I am using Azure Function (NodeJs) to dynamically add content to templates using handlebars and return me the final html email, which works great. I have separated sections of the template into different files (header, footer, intro etc.) and I have included them using mj-include.

currently this is what I'm doing.

  • I first read the main mjml file.

    var mjmlData = fs.readFileSync(filePath, 'utf8');

  • then run mjml2html to get the template rendered

    var htmlTemplateObject = mjml2html(mjmlData, {filePath: filePath});

  • Then I run handlebars to inject dynamic content

    handlebars.compile(htmlTemplateObject.html)(req.body.data)

I have to run mjml2html first before using handlebars to inject data dynamically as otherwise handlebars won't pick content in the files that I have included with mj-include. Because of this, if I have for example say a p tag in the dynamic content, the styles won't get inlined because I have already converted my mjml template to html before running handlebars.

Is there a way for me to get the full mjml (with content from file included using mj-include) rendered into a string before running mjml2html?

Any help much appreciated as something like mjml2string would make this a perfect solution.

Amila
  • 3,711
  • 3
  • 26
  • 42

2 Answers2

1

I went through the mjml github repository to find out how it works as MJML CLI needs to somehow combine the files in mj-include elements before converting it to html. I found the code which include the files and generate the MJML document in mjml-core/lib/includeExternal.

All I had to do was to import it and use it as

let mjmlTemplate = mjmlInclude(mjmlBaseTemplate, {filePath: mjmlBaseTemplateFilePath})

Then I ran handlebars to inject dynamic content into the template and finally run mjml2html(mjmlTemplate) to get the final html file. Doing so injected my styles within mj-style to html tags in the dynamic content.

Amila
  • 3,711
  • 3
  • 26
  • 42
  • Impressive! Can anyone update this technique? Has there been related MJML refactoring since then (4.2 to 4.10.1?) Is the above line an `mjml2mjml-with-includes`? Then use `mjml2html` and `handlebars`? – BaldEagle Jul 03 '21 at 20:35
1

I don't claim the answer as mine, but it serves as an update to the above. I saw this on the MJML Slack from the MJML team. Applies to source code for MJML 4.10.1.

Hi ! You can use the mjml parser as we use it in mjml-core here https://github.com/mjmlio/mjml/blob/master/packages/mjml-core/src/index.js#L128-L135 and convert back the json to xml (we have a internal helper for that too https://github.com/mjmlio/mjml/blob/master/packages/mjml-core/src/helpers/jsonToXML.js )

Don't forget to require the full mjml package first to load register every standard components

BaldEagle
  • 918
  • 10
  • 18