Matt Hellige
Matt Hellige

Reputation: 118

How to write a template expanding to multiple elements?

I'd like to write a knockout.js template which should expand into a set of table cells. In other words, something like:

<tr>
    <td>Cell one</td>
    <td>Cell two</td>
    <div data-bind="template: ..."></div>
    <td>Cell six</td>
</tr>
<script id="..." type="text/html">
    <td>Cell three</td>
    <td>Cell four</td>
    <td>Cell five</td>
</script>

But the div tag isn't allowed in the tr, of course, and I can't figure out any way to coax knockout to replace the div tag with the template expansion, rather than nesting the expansion inside the div.

Anybody know a way to accomplish this?

Upvotes: 1

Views: 524

Answers (1)

Steve Michelotti
Steve Michelotti

Reputation: 5213

You can do this with the new "containerless" templates like this:

<tr>
<td>Cell one</td>
<td>Cell two</td>    
<!-- ko foreach: names -->
    <td>Cell three<span data-bind="text: name"></span></td>
    <td>Cell four</td>
    <td>Cell five</td>
<!-- /ko -->
<td>Cell six</td>

with js like this:

$(function() {
var viewModel = {
    names: ko.observableArray([ { name: "Bob"}, {name: "John"}])
};
ko.applyBindings(viewModel);

});

Here is a jsfiddle that shows it in action: jsfiddle

Here is a jsfiddle that shows it without the foreach: jsfiddle

Upvotes: 2

Related Questions