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.
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.