Skip to content

Instantly share code, notes, and snippets.

@yuanxu
Created July 22, 2013 06:31
Show Gist options
  • Save yuanxu/6051698 to your computer and use it in GitHub Desktop.
Save yuanxu/6051698 to your computer and use it in GitHub Desktop.
knockoutjs & underscore template
/* ---- Begin integration of Underscore template engine with Knockout. Could go in a separate file of course. ---- */
ko.underscoreTemplateEngine = function () {
};
ko.underscoreTemplateEngine.prototype = ko.utils.extend(new ko.templateEngine(), {
renderTemplateSource: function (templateSource, bindingContext, options) {
// Precompile and cache the templates for efficiency
var precompiled = templateSource['data']('precompiled');
if (!precompiled) {
precompiled = _.template("<% with($data) { %> " + templateSource.text() + " <% } %>");
templateSource['data']('precompiled', precompiled);
}
// Run the template and parse its output into an array of DOM elements
var renderedMarkup = precompiled(bindingContext).replace(/\s+/g, " ");
return ko.utils.parseHtmlFragment(renderedMarkup);
},
createJavaScriptEvaluatorBlock: function (script) {
return "<%= " + script + " %>";
}
});
ko.setTemplateEngine(new ko.underscoreTemplateEngine());
/* ---- End integration of Underscore template engine with Knockout ---- */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment