Search code examples
javagoogle-app-enginevelocityfreemarkerstringtemplate

Any tutorials on setting up a templating framework on GAE (Java)?


I'm trying to format our emails by using HTML-formatted templates on Google App Engine (using Java), but for the life of me I cannot find a decent tutorial for how to set this up.

I've tried looking at StringTemplate, but I cannot find any examples where a stand-alone template is loaded from a servlet's context and used as a formatter.

Can anyone help? I'm open to any suggestions, such as Velocity or FreeMarker, so long as they run on GAE.

Thanks


Solution

  • Figured out how to do it.

    The documentation for StringTemplate can be very confusing. The latest version (version 4) has different classes than previous versions (ST instead of StringTemplate, STGroup instead of StringTemplateGroup, etc)

    It also has an external dependency on 'antlr'. Per these instructions (link contains links to jars needed), put the 'antlr' and 'SimpleTemplate' jars in the WEB-INF/lib directory on the server.

    Version 2 introduced template 'groups', which as far as I can tell, are required for loading a template from a file on a web server.

    So to get it working, I had to define a template group file, with the following content, named emailTemplate.stg

    html_format(keyToReplace1, keyToReplace2) ::= <<
    <html>
    <body>
      <div>
        This is $keyToReplace1$
        <br/>
        This is $keyToReplace2$
      </div>
    </body>
    </html>
    >>
    

    I then had to ensure this file was accessible by my code via a relative URL. This is easily testable by going to the URL in the browser, such as at: localhost:8888/templates/emailTemplate.stg

    Then, to use this template, I used the following code:

    STGroup g = new STGroupFile("templates/emailTemplate.stg", '$', '$');
    ST emailTemplate = g.getInstanceOf("html_format");
    emailTemplate.add("keyToReplace1", "value for the first key");
    emailTemplate.add("keyToReplace2", "value for the second key");
    String result = emailTemplate.render();