I was working on a BackboneJS project recently that was using UnderscoreJS for templating and started wondering if its possible to invoke UnderscoreJS recursively.
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!