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

810 Views Asked by At

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

2

There are 2 best solutions below

1
On BEST ANSWER

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();
2
On

You can load templates from the class path just like any other input stream to use in StringTemplate.

import org.antlr.stringtemplate.*;
import org.antlr.stringtemplate.language.*;

StringTemplate hello = new StringTemplate("Hello, $name$", DefaultTemplateLexer.class);
hello.setAttribute("name", "World");
System.out.println(hello.toString());

you can look at the JavaDoc to see how to load a file/resource using an input stream, using Class.getResourceAsString(), the file needs to be on the classpath usually in the default package of your .war ( ie in the root of /lib ) with the .class files.

Read the resource into a String and substitute the first paramater with the contents, or use one of the Stream constructors of StringTemplate.

It is really simple.