Ian Obermiller

Part time hacker, full time dad.

Precompile Handlebars Template in .NET using Jurassic

Posted 2012-07-25

The awesome Handlebars.js templating library, a superset of Mustache, has functions built-in for precompiling a template to a javascript function. Unfortunately, the instructions are only for Node.js. Using the Jurassic javascript compiler for .NET, it is simple to precompile your Handlebars template in C# and serve up the template functions in your javascript:

using Jurassic;

public string PrecompileHandlebarsTemplate(string name, string template)
{
    var engine = new ScriptEngine();
    engine.ExecuteFile(@"handlebars-1.0.0.beta.6.js");
    engine.Execute(@"var precompile = Handlebars.precompile;");
    return string.Format("var {0} = Handlebars.template({1});", 
        name, engine.CallGlobalFunction("precompile", template).ToString());
}

The function can be used as follows:

PrecompileHandlebarsTemplate("greet", "<div>{{hello}} world!</div>");

And will output a javascript function as a string, something like this:

var greet = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
  helpers = helpers || Handlebars.helpers;
  var buffer = "", stack1, foundHelper, self=this, functionType="function", helperMissing=helpers.helperMissing, undef=void 0, escapeExpression=this.escapeExpression;


  buffer += "<div>";
  foundHelper = helpers.hello;
  stack1 = foundHelper || depth0.hello;
  if(typeof stack1 === functionType) { stack1 = stack1.call(depth0, { hash: {} }); }
  else if(stack1=== undef) { stack1 = helperMissing.call(depth0, "hello", { hash: {} }); }
  buffer += escapeExpression(stack1) + " world!</div>";
  return buffer;});

Which you can then use easily in the rest of your javascript (after including handlebars.runtime.js):

$('body').append(greet({ hello: 'Bonjour' }));

You can find a working example at JS Bin.