build table with jquery template plugin

desperate man picture desperate man · Feb 19, 2011 · Viewed 9.2k times · Source

I feel helpless. I'd like to build a table with jquery template plugin and then fill table with the data from the response which looks like this:

[
     [
        {Row:0,Col:0},
        {Row:0,Col:1},
        {Row:0,Col:2},
        {Row:0,Col:3},
        {Row:0,Col:4},
        {Row:0,Col:5},
        {Row:0,Col:6}
     ],
     [
        {Row:1,Col:0},
        {Row:1,Col:1},
        {Row:1,Col:2},
        {Row:1,Col:3},
        {Row:1,Col:4},
        {Row:1,Col:5},
        {Row:1,Col:6}
     ]
]

So the table is supposed to be with 2 rows and 7 columns in each row.

Here's the code I stuck with:

$('#trTemplate').tmpl(result.d).appendTo('#containerTable');

<script id="trTemplate" type="text/x-jquery-tmpl">
    {{each $data}}
        {{if $index < 2}}
            <tr>
                {{tmpl($value) "#tdTemplate"}}
            </tr>
        {{/if}}
    {{/each}}
</script>

<script id="tdTemplate" type="text/x-jquery-tmpl">
    {{each $data}}
        <td>${Col}</td>
    {{/each}}
</script>

<table id="containerTable">
</table>

I tried different approaches, changed the look of the data source which works fine, tried to build table without template, but I really need to know how to build a table with having such data source and using templates? Thanks for the help.

Answer

RP Niemeyer picture RP Niemeyer · Feb 19, 2011

Unless I am misunderstanding your needs, here is a working sample: http://jsfiddle.net/rniemeyer/cEvJs/

One thing to remember is that if you pass an array into the template function it automatically evaluates it for each item in the array. So, your template can be as simple as:

<script id="trTemplate" type="text/x-jquery-tmpl">
       <tr>
            {{each $data}}
                 <td>${Col}</td>
            {{/each}}
       </tr>
</script>