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
Remove All Special Characters with Regexp
How to Load Local Script Files as Fallback in Cases Where Cdn Are Blocked/Unavailable
Safari 3Rd Party Cookie Iframe Trick No Longer Working
JavaScript - Get Portion of Url Path
Where to Write to Localstorage in a Redux App
How Many Bytes in a JavaScript String
JavaScript - How to Extract Filename from a File Input Control
Canvas.Todataurl() Securityerror
Jquery to Loop Through Elements with the Same Class
How to Set Multiple CSS Styles in JavaScript
Get the Index of the Object Inside an Array, Matching a Condition
How to Copy Static Files to Build Directory with Webpack
Getting Unexpected Token Export
Filtering Array of Objects with Arrays Based on Nested Value