pixelboy
pixelboy

Reputation: 729

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 the 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.

Upvotes: 0

Views: 1815

Answers (2)

patridge
patridge

Reputation: 26565

{{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"));

Upvotes: 1

Evan
Evan

Reputation: 6115

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}}

Upvotes: 0

Related Questions