您的语法将不适用于剔除默认模板引擎,因为它使用 DOM。如果您需要这样做,请使用基于字符串的外部模板引擎(它将您的模板视为字符串,并将使用正则表达式和字符串操作,因此您将能够通过条件渲染开始/结束标记来完成此技巧)。您使用下划线 js 的示例:
http://jsfiddle.net/2QKd3/5/
HTML
<h1>Table breaking</h1>
<ul data-bind="template: { name: 'peopleList' }"></ul>
<script type="text/html" id="peopleList">
<table>
<tbody>
{{ _.each(model(), function(m, idx) { }}
{{ if (idx % 4 == 0) { }}
<tr>
{{ } }}
<td>
<label>{{= m.Value }}</label>
</td>
<td>
<input type="checkbox" data-bind="checked: m.IsChecked"/>
</td>
{{ if (idx % 4 == 3) { }}
</tr>
{{ } }}
{{ }) }}
</tbody>
</table>
</script>
Javascript(这包括此处描述的下划线集成 - http://knockoutjs.com/documentation/template-binding.html
_.templateSettings = {
interpolate: /\{\{\=(.+?)\}\}/g,
evaluate: /\{\{(.+?)\}\}/g
};
/* ---- 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 ---- */
var viewModel = {
model: ko.observableArray([
{ Value: '1', IsChecked: 1 },
{ Value: '2', IsChecked: 0 },
{ Value: '3', IsChecked: 1 },
{ Value: '4', IsChecked: 0 },
{ Value: '5', IsChecked: 1 },
])
};
ko.applyBindings(viewModel);
PS:但最好避免使用表格进行 html 布局。您的示例可以使用具有更简洁代码的内联块元素呈现。