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 cu开发者_如何学Crrently 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?
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/
jt - there's a fantastic example of this at dave wards encosia that will allow you to leverage nice compact composition on jquery templates. take a mosey over to:
http://encosia.com/2010/12/02/jquery-templates-composite-rendering-and-remote-loading/
I think it'll get you onto the path of convention over configuration on this type of thing, it did me.
var data = ['a', 'b', 'c'];
var list = $('<ul/>');
$.each(data, function(idx, val) {
$('<li/>').html(val).appendTo(list);
});
$('body').append(list);
This does the job without any string representations. However, the code in your question is much more efficient as there is no need for a DOM manipulation for every item.
Reading http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly about the performance issue with DOM insertions is a good idea.
Edit: Looking at the other answer now it seems I've misread the question. I'll leave this answer here anyway so people see that way including the comment why it's bad.
精彩评论