Search code examples
javascriptjqueryjquery-templates

appending an array in to jquery template


I am trying to append an array items[] in my webpage using jquery template.

items=[{'name' => 'test',
        'values' => 
           [
            {
            'ver' => 2,
            'count' => 469,
           },
           {
            'ver' => 2,
            'count' => 445,
            }]},

        {'name' => 'test2',
        'values' => 
           [
           {
            'ver' => 4,
            'count' => 604,
            },
           {
            'ver' => 5,
            'count' => 469,
            }]}]

append code used is $("#div").tmpl(items).appendTo("#divTable");

I ve specified ${name} to get the printed output fruit and Veg, since name is another array, how do I get it printed??? Ive used ${values.ver}, it doesnt wrk...


Solution

  • To iterate over an array within a jQuery.tmpl, you can use the {{each}}-template-language-construct, or {{tmpl}}.

    "Each" will just iterate over every item, automatically putting it in $index and $value. An example:

    ${name} <br />
    {{each values}}
      ver: ${$value.ver} <br />
      count: ${$value.count} <br />
    {{/each}}
    

    Alternatively, "tmpl" will allow you to create a new template, meant specifically for the sub-arrays.