Search code examples
groovymjml

Is it possible to render MJML template with the MarkupTemplateEngine in a Groovy script?


I am trying to use the MarkupTemplateEngine to render a template in MJML but after trying for a while I am starting to doubt if it is possible. Is it possible or not ? If yes, I would like to have an example that works to test with.

So far what I did :

import groovy.text.markup.*

String mjmlTemplate = '''
mjml {
    mj-head {
        mj-title('Hello World')
        mj-preview('This is a preview text')
    }
    mj-body {
        mj-section {
            mj-column {
                mj-text('Hello World from MJML')
            }
        }
    }
}
'''

TemplateConfiguration config = new TemplateConfiguration();
MarkupTemplateEngine engine = new MarkupTemplateEngine(config);

def template = engine.createTemplate(mjmlTemplate)
def renderedMJML = template.make().toString()

println renderedMJML

the error I got :


Caught: java.lang.NullPointerException: Cannot invoke method minus() on null object
java.lang.NullPointerException: Cannot invoke method minus() on null object
        at GeneratedMarkupTemplate0$_run_closure1$_closure2.doCall(GeneratedMarkupTemplate0:4)
        at GeneratedMarkupTemplate0$_run_closure1$_closure2.doCall(GeneratedMarkupTemplate0)
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
        at GeneratedMarkupTemplate0$_run_closure1.doCall(GeneratedMarkupTemplate0:3)
        at GeneratedMarkupTemplate0$_run_closure1.doCall(GeneratedMarkupTemplate0)
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
        at GeneratedMarkupTemplate0.run(GeneratedMarkupTemplate0:2)
        at test.run(test.groovy:30)
        at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)

If I test with rendering HTML it works fine.


Solution

  • The "template" is just Groovy code (it is function calls with closures and maps basically). So you have to write the "methods" in a way, Groovy can parse and call them. So mj-body parses to mj.minus(body) in a sense, hence the error. You can use quotes for the method-names/tags though. E.g.

    import groovy.text.markup.*
    
    String mjmlTemplate = '''
    mjml {
        'mj-head' {
            'mj-title'('Hello World')
            'mj-preview'('This is a preview text')
        }
        'mj-body' {
            'mj-section' {
                'mj-column' {
                    'mj-text'('Hello World from MJML')
                }
            }
        }
    }
    '''
    
    TemplateConfiguration config = new TemplateConfiguration();
    MarkupTemplateEngine engine = new MarkupTemplateEngine(config);
    
    def template = engine.createTemplate(mjmlTemplate)
    def renderedMJML = template.make().toString()
    
    println renderedMJML