Created
July 22, 2013 06:31
-
-
Save yuanxu/6051698 to your computer and use it in GitHub Desktop.
knockoutjs & underscore template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ---- 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