How to Use Underscore.Js as a Template Engine

underscore.js precompiled templates using

I finally found this solution. I can't say that this is elegant solution, but it works.
For my example:

var a = eval('[' + tplc + ']')[0];
a({});

Using Underscore.js template within Knockout.js doesn't allow me to use if binding

if binding uses knockout template engine, use underscore template instead

{{ if (test) { }}
<div data-bind="text:testString">test</div>
{{ } }}

See fiddle

Underscore.js template compilation

The _.template function has changed a little bit, assuming you're on the latest version, it now produces a function instead of the compiled HTML which you have to call with the data you want to be displayed.

var temp = "<div> Hello <%= names %> </div>";
var html = _.template(temp);
console.log(html({names:'world'}));

"<div> Hello world </div>"

Run Template in Template (recursion) within underscore.js template engine

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:

var templateFn = _.template($('#navigation_template').html());

$(this.el).html(templateFn({model: this.model, templateFn: templateFn}));

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:

<script id="navigation_template" type="text/template">
<div><%= model.escape('title') %>
<% _.each(model.children, function(child) { %>
<%= templateFn(child, templateFn) %>
<% }); %>
</div>
</script>

Good luck. I hope this works for you

Using % in Underscore.js templating without parsing it

If your final output is going to be HTML, you could replace < and > with their HTML escape code thingers:

_.template('<%= name %> ### <%= name %>', { name: 'foo' });

You could also modify Underscore's template settings to support these things, so that <%= ... %> means nothing to Underscore:

_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var t = _.template('{{name}} ### <%= name %>', { name: 'foo' });


Related Topics



Leave a reply



Submit