Recursive templates with UnderscoreJS

I was working on a BackboneJS project recently that was using UnderscoreJS for templating and started wondering if its possible to invoke UnderscoreJS recursively.

At face value, the _.template function simply takes a template string and converts it to a first class Javascript function so I figured it would be possible. Out of curiosity, I decided to take a look at how the _. function is actually implemented:

Not any real surprises there – it basically does a series of string replaces on the template you pass in to interpolate any variables you want outputted, converts blocks you want evaluated to regular Javascript, and then injects the object you passed in into the local scope.

Then, the “magic” happens at “var render = new Function(settings.variable || ‘obj’, ‘_’, source);” where a new function is created with a “print” function locally defined and your template converted to a Javascript function.

Here is the “source” string that is passed into “new Function”:

That is the dynamic function generated for the following template:

Since its looking for the “template” function in the global scope it looks like everything should work fine. To test it, I decide to take the Fibonacci sequence and generate boxes for each of the numbers in the sequence up to some N.

Theres a live demo running at http://twitlabs.net/us/ and a Gist of the code is replicated below:

Just for fun, you can also change how the boxes are arranged by toggling between “Stacked” and “Cascaded”.

Anyway, fair warning – I imagine there are some performance implications regarding doing this as well as computational limits. You could potentially cause a stack overflow by consuming your entire stack via the recursion.

As always, questions, comments, concerns welcome!