第一种使用方式:
HTML:
<ul data-bind="template: { name: 'peopleList' }"></ul><script type="text/html" id="peopleList"><% _.each(people(), function(person) { %><li><b data-bind="text: person.name"></b> is <%= person.age %> years old</li><% }) %> </script>
JS:
/* ---- 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 efficiencyvar 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 elementsvar 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 ---- */var viewModel = {people: ko.observableArray([{ name: 'Rod', age: 123 },{ name: 'Jane', age: 125 },]) };ko.applyBindings(viewModel);
代码演示
第二种使用方式:
HTML代码段:
<div class="l_box_temp" id="side-userInfo"></div>
JS代码段:
define(['knockout','jquery','underscore','model''text!home/view/side-userInfo.html'], function(ko, $, _, model, viewBaozhang, template) {var ViewModel = function() {var self = this;self.viewUserInfo = $('#side-userInfo');self.template = _.template(template);self.html = '';self.grade = '';self.initialize = function() {model.getData(function(res){self.html = self.template(res);self.viewUserInfo.html(self.html);self.grade = res.grade;setTimeout(function(){ko.applyBindings(self, $('body')[0]);},0)});}} });
第二种方式的优点是可以从外部引入模板不需要把模板放在页面上,可以在多个页面重用。