Search code examples
knockout.jsjquery-templates

Creating a multicolum HTML table with jQuery templates and knockoutjs


I have the following code (also in a jsfiddle):

<table>
    <thead><tr><th>Equation</th><th>Equation</th></tr></thead>
<tbody data-bind="template: {name: 'equationTemplate', foreach: equations}"></tbody>
</table>

<script language="javascript" type="text/javascript">

</script>

<script type="text/x-jquery-tmpl" id='equationTemplate'>
    <!-- In here I want to be able to break it up into two 
    columns of two rather than one column of four-->
    <tr>
        <td>${first}+${second}=<input data-bind="value: answer"/></td>
    </tr>
</script>

With this JS:

$(document).ready(function () {

    var viewModel = {
        equations: ko.observableArray([
            { first: 1, second: 2, answer: 3 },
            { first: 4, second: 4, answer: 8 },
            { first: 10, second: 10, answer: 20 }, 
            { first: 5, second: 5, answer: 10}])
    };

    ko.applyBindings(viewModel);
});

How would I modify the template to output this in a table of two rows and two columns? Equations 10+10=20 and 5+5=10 should appear in the second column.

Any help greatly appreciated.


Solution

  • One option is to switch to {{each}} instead of the foreach option of the template binding, so that you have access to the index. The disadvantage to using {{each}} is that your template will be re-rendered completely if any equations are added/removed dynamically.

    It would look like:

    <table>
        <thead><tr><th>Equation</th><th>Equation</th></tr></thead>
    <tbody data-bind="template: { name: 'equationTemplate', foreach"></tbody>
    </table>
    
    <script type="text/x-jquery-tmpl" id='equationTemplate'>
        {{each equations}}
            {{if $index % 2 == 0}}<tr>{{/if}}
                <td>${first}+${second}=<input data-bind="value: answer"/></td>
            {{if $index % 2 == 1}}</tr>{{/if}}   
        {{/each}}
    </script>
    

    Sample here: http://jsfiddle.net/rniemeyer/QESBn/1/

    Another alternative would be to build a dependentObservable that represents your data in a structure that maps to rows/columns.

    Here is a sample: http://jsfiddle.net/rniemeyer/QESBn/2/