I am using backbone.js and underscore.js to build an javascript application. Since hours of reading and trying to run a template within a template like below, it is getting more and more frustrating.
My template using the build in underscore.js template engine:
<script id="navigation_template" type="text/template">
<div><%= title %>
<% _.each(children, function(child) { %>
<% render_this_template_recursively(child) %>
<% }); %>
</div>
</script>
I would like to render this template for every child element ( render_this_template_recursively(child) ).
How can I do this?
Thanks
I implemented this recently using backbone-relational. I created a fiddle that I thought might be helpful if you want to see a working solution: http://jsfiddle.net/blaisco/ADKrK/
I've posted the relevant bits below.
The view:
The html/template:
A recursive template can look something like this:
First, pre-compile your template:
Then call it while passing both your data and the template itself:
I've not personally tried this but _.template returns a function (I've named it templateFn to emphasize that), so you could pass it into the template like this:
Notice that i'm passing in the whole model (assuming that your model has a children property which is itself a collection of backbone models) and your template would be changed to:
Good luck. I hope this works for you
I just successfully tried this. I tested it with only pure UnderscoreJS, no BackboneJS but functionally it shouldn't matter.
Here is the code:
I've tried to use example presented by timDunham and Ates Goral, but it did not work for me, so I've made a little upgrade for it. Find it below.
view:
and template:
And it works pretty good for me. The main difference, as you can see, is the passing configuration object into templateFn, instead of arguments. Hope you'll find it useful.