Search code examples
jqueryjquery-templates

Jquery Templates: One parent container, many children?


Using jquery templates, I want to create a list. I want one parent <ul /> element with many <li /> elements, resulting in:

<ul>
  <li>One</li>
  <li>Two</li>
</ul>

My data is similar to this:

var data =
[
  { val: 'One' },
  { val: 'Two' }
]

Currently, the child <li /> template looks like this:

<script id="child-tmpl" type="text/x-jquery-tmpl">
    <li>
      ${val}
    </li>
</script>

To get the result I want, I'm currently doing this:

$('<ul></ul>').append($("#answer-tmpl").tmpl(data));

But this only half-embraces the spirit of Jquery Templates. I don't want to do any string version of my markup (as above).

Rather, does anyone have an idea on what the parent <ul /> Jquery Template might look like?


Solution

  • Instead of giving tmpl an array, give it an object which has the array as a field:

    $("#answer-tmpl").tmpl({ data: data });
    

    Then you can modify your template like this:

    <script id="answer-tmpl" type="text/x-jquery-tmpl">
      <ul>
        {{each data}}
        <li>
          ${val}
        </li>
        {{/each}}
      </ul>
    </script>
    

    You can see a working example at http://jsfiddle.net/YNm3n/