I can write that Javascript template library in 5 lines

Do you want to write your own Mustache or Underscore templating library real fast?

I’m porting an application written in 2007 using prototype and YUI into an Angular framework.  This application is used in many hospitals around the country to process medical data such as patient events, MRIs, genetic data etc.  Different groups around the country have written plugins for the framework, so the new AngularJS framework must be backwards compatible with the old plugins. The plugins communicate with “cells” on the server using XML messages.  The messages are implemented as XML templates with replacement values like <user>{{{username}}}</user> using Prototype’s Template.  Prototype doesn’t play terribly well with AngularJS (almost immediately death, actually).  Angular’s $interpolate is probably a little two heavy-handed and choked on the input anyway (I think the the double-quotes int he namespaces were giving it problems). So I needed to replace Prototype’s Template.

I couldn’t believe how easy it was to solve!

As the old saying goes, I had a problem.  I knew I could solve it with RegEx, therefore, I had two problems. Actually the RegEx problem is pretty simple – look for three open braces in a row [\{]{3,3}, followed anything that wasn’t three closed braces in a row [\}]{3,3}.  The real trick here that made it easy is a variation in Javascript’s String.replace that excepts a function (instead of a string) as the replacement value.  The function is passed the match, and the function just looks up the match in the replacement values, thus leading to the dynamic replacement effect that’s needed.

I2b2Template.prototype.evaluate = function (templateString, replacements) {
    return templateString.replace(/[\{]{3,3}[\w]*([^}]+)[\w]*[\{]{3,3}/g, function (captured) {
        var captureWithoutBraces = captured.substring(3, captured.length-3);
        if (angular.isDefined(replacements[captureWithoutBraces])) {
            return replacements[captureWithoutBraces];

Obviously it’s not too fancy as a templating system.  It doesn’t work with trees of values (user.name).  It only works with triple braces, but that can be easily changed to anything else (must replace the hard coded regex with RexEx(..).  These features were not the requirement and there’s no need to do more than necessary.  Keeping it simple.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: