A templating system allows generating the text for HTML, emails, SQL, etc. without hardcoding the text in Java. This greatly improves the managability of your Java code and makes it much easier to make changes. While the templating system presented below is simple to implement, it still supports variable substitutions, condition logic, loops, etc. This templating system requires Jelly and is implemented in the provided JellyScript Wrapper Class.

Let’s say you have a welcome email that should look something like this…

Hello, Kent, thanks for creating a Trendics account at
www.trendics.com.  Your new user name and password is...

   User: kent13600
   Password: my.secret

Be sure to checkout the instant website speed
check at http://tools.trendics.com/sc.

- Trendics Support Team

Instead of hardcoding this text within a Java class, you can use the provided JellyScript Wrapper Class to define a template that looks like this…

Hello<jelly:if test='${!empty FirstName}'>,
${FirstName}</jelly:if>, thanks for creating a
Trendics account at www.trendics.com.  Your new
user name and password is...

   User: ${UserName}
   Password: ${Password}

Be sure to checkout the instant website speed
check at http://tools.trendics.com/sc.

- Trendics Support Team

The LastName and Password variables are simply substituted at the appropriate locations. The <jelly:if test=’${!empty FirstName}’>, ${FirstName}</jelly:if> logic is only adding a comma and the FirstName if the FirstName is not blank.

As another example, you can use this templating system to generate SQL…

SELECT *
FROM Employee
WHERE State='${State}'
    <jelly:if test='${!empty City}'>
        AND City='${City}'
    </jelly:if>

In the SQL template above, a State filter parameter is required and a City filter parameter may optionally be included.

The examples above did only simple variable substitution and a bit of conditional logic; however, Jelly supports a whole range of tags supporting various types of logic constructs including loops, creating Java objects, calling methods on Java objects, etc. (see here).

Here is an example of the Java code necessary to execute a template…

 public static void main(String[] args) {
    if (logger.isLoggable(Level.FINE)) logger.fine("main()");

    try {
        // Create a template
        final StringBuffer sb = new StringBuffer();
        sb.append("Hello<jelly:if test='${!empty FirstName}'>");
        sb.append(", ${FirstName}</jelly:if>, ");
        sb.append("thanks for creating a Trendics account ");
        sb.append("at www.trendics.com.  ");
        sb.append("Your new user name and password is...\n");
        sb.append("\n");

        sb.append("   User: ${UserName}\n");
        sb.append("   Password: ${Password}\n");
        sb.append("\n");
        sb.append("Be sure to checkout the instant website ");
        sb.append("speed check at http://tools.trendics.com/sc.\n");
        sb.append("\n");
        sb.append("- Trendics Support Team\n");

        // Create the JellyScript instance
        final JellyScript jellyScript = new JellyScript(sb.toString());

        // Create the variables needed by the template
        final Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("FirstName", "Kent");
        variables.put("UserName", "kent13600");
        variables.put("Password", "my.secret");

        // Execute the script to merge the variables with the template
        final String result = jellyScript.execute(variables);
        System.out.println(result);
    }
    catch (Exception e) {
        logger.log(Level.SEVERE, "main()", e);
    }
}

Note that defining the template within Java code sort of defeats a key benefit of templating — you would normally define your templates within an XML configuration file or store the templates in their own files.

Bookmark at:
StumbleUpon | Digg | Del.icio.us | Dzone | Newsvine | Spurl | Simpy | Furl | Reddit | Yahoo! MyWeb
4 Responses to “Simple Templating System for Java”
  1. You don’t need to use StringBuilder/Buffer to concatenate hardcoded strings in your source code. Just use ‘+’ and the compiler will turn it into a single String.

    See StringBuilder vs StringBuffer vs String.concat - done right for details.

    String template=
    "Hello<jelly:if test='${!empty FirstName}'>,\n"+
    "${FirstName}</jelly:if>, thanks for creating a\n"+
    "Trendics account at http://www.trendics.com. Your new\n”+
    “user name and password is…\n”+
    “\n”+
    ” User: ${UserName}\n”+
    ” Password: ${Password}\n”+
    “\n”+
    “Be sure to checkout the instant website speed\n”+
    “check at http://tools.trendics.com/sc.\n”+
    “\n”+
    “- Trendics Support Team”;

    Formatting a piece of text this way is pretty easy with regex search’n'replace. Just replace \n with \\n"+\n", add the leading and trailing quotes, a semicolon, and you’re done. (If anything needs escaping do that beforehand.)

  2. You call this simple? Ever hear of Velocity?

  3. Grails provides templates anyways…so just use that instead

  4. The blog.trendics.com is interesting resource, good job, admin.
    Good luck.

Leave a Reply