jquery templates iterate on value, not number of keys
Using the jquery template plugin is pretty straighforward, but i'm facing an issue quite simple to explain.
I'd like to iterate in my template based on t开发者_Go百科he value of one key I get;
for example num_lines : 15
{{each (var i = 0; i < ${num_lines}; i++)}}
poet
{{/each}}
While logic is ok, it does'nt do the trick. Any idea where i'm wrong ? Thanks.
{{each}}
expects some sort of collection. You will need to build up a collection from your count to use it.
You could simply create a helper function for your template and pass it in the options parameter. Here's a sample jsFiddle jQuery template that uses an each-friendly custom function. You simply give it the word you want repeated and how many times and {{each}}
does the work for you.
Template
<script id="itemTemplate" type="text/x-jquery-tmpl">
<ul>
{{each(i, prop) $item.makeArrayForEach("poet", $data.someInteger)}}
<li>${prop}</li>
{{/each}}
</ul>
</script>
JavaScript
var makeArrayForEach = function (word, size) {
var i, result = [];
for (i = 0; i < size; i++) {
result.push(word);
}
return result;
};
$("#itemTemplate").tmpl(yourObject, {
makeArrayForEach: makeArrayForEach
}).appendTo($(".results"));
i don't think each is meant to use in this fashion. the only thing I can think of is doing:
javascript:
var poet = [{
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"},
{Poet:"poet"}
}];
HTML:
{{each Poet}}
${$value}
{{/each}}
精彩评论