mjmlio/mjml

Convert JSON MJML templates back to standard MJML

Closed this issue · 6 comments

I'm working with Mailjet's templates API. Templates get returned from this in JSON format. Is there an easy way to convert from this JSON format to standard MJML?

My end goal is to compile these templates to HTML, so I might be able to draw the line from the other side and get the library I'm using to do this. But it'd be helpful to convert back to standard MJML so that it's more portable.

Awesome, thank you for the quick response!

I reimplemented this in Ruby as follows:

module Mjml
  class ToXml
    def initialize(source)
      @source = source
    end

    def call
      CGI.unescape_html(Nokogiri::XML::Builder.new { |xml| build_tag(xml, **@source.deep_symbolize_keys) }.to_xml)
    end

    def build_tag(builder, tagName:, attributes: {}, children: [], content: '', **_kwargs)
      builder.public_send(tagName, CGI.unescapeHTML(content), **attributes) do
        children.each { |child| build_tag(builder, **child) }
      end
    end
  end
end

Thank you @boardfish!
May I ask a question: we have a table storing the mjml json source in the database, we want to send an email with actionmailer with the compiled source. Does this work based on your experience?
In a mailer view you would call something like Mjml::ToXml.new(@campaign.mjml_json).call? Thanks!

You'd save the output of Mjml::ToXml.new(@campaign.mjml_json).call using something like this:

      def create_local_cache_of_template(campaign)
        mailer_subdir, basename = campaign.figure_out_mailer_path_somehow
        mailer_dir = "#{Rails.root}/app/views/#{mailer_subdir}"
        Dir.mkdir mailer_dir unless Dir.exist? mailer_dir
        File.open("#{mailer_dir}/#{basename}.mjml", 'w') { |f| f.write(campaign.mjml_json) }
      end

...and use mjml-rails to process it.

However, unless you're also templating variables as you do in ERB, you might fall foul of sighmon/mjml-rails#85. So I actually forewent this solution in favor of using Mailjet's compiled HTML content with the regex listed in that issue.

Thank you for the great answer, that's indeed our use case. We're evaluating options atm, from what you're saying regarding variables, it's probably better to move towards a mjml json with variables placeholders, converted to html via api or serverless function using node package, then to action mailer for sending..I just wonder about performances