Monday, July 9, 2012

Simple(r) String Templates with Commons Lang

Whenever I have a need to use string templating in a project, I reflexively turn to Velocity, which works great, but it:
  • is "heavy": can be difficult to get into a project and functional, has some quirks with classloaders and logger systems, etc
  • is old: last updates were back in 2010
Velocity is also loaded with features like control constructs, loops, branches, etc, which seem like overkill when all I really need to do is format email notifications with some variables (I've already gone the route of client-side view templates for my UI stuff these days).

I know there are a million ways to solve this using homegrown regex's and other such things, but I found a convenient helper in Commons Lang3: StrSubstitutor. It allows you to replace variables in a string, denoted by:
I've written a simple wrapper around it, which can pull a template string from a file on the classpath, caching it using a simple WeakHashMap.  This could be extended to use the nicer caching framework found in the fantastic Google Guava project, perhaps.

An example use of this class might be to stick a template text file into src/main/resources/templates/foo.template (for all of you fellow Maven'rs out there!), and invoke it like:
String output = Templates.template("templates/foo.template")
                         .value("foo", "bar")
                         .value("other", "val")

No comments: