4
votes

I'm using JsRender to render a template client-side. However, I'm unable to use the for loop tag to repeat an html-portion of the block because it seems to accept only arrays or objects. Instead, my JSON return a variable which is a number (the number of times I should repeat the block). How can I repeat html N times using JsRender?

2
Instead of putting -1 and going away, please comment so that if my question is not clear I can edit it - Stefano
Have you tried the whole html block in an array? - Franz Noel
what do you mean by "whole block in an array"? The block is a simple html portion that I should repeat N times. With PHP it's a simple range-based for loop, however I don't find a way to do it with JsRender - Stefano
if you have a block with the code <div>Something that I want to write</div>. Then, you can put this whole long "string" in an array. One block of html code is equivalent to 1 array. Then, repeat the array. - Franz Noel
this won't work because I don't get from the response an HTML block but only a number saying how many times it must be repeated - Stefano

2 Answers

4
votes

I extended @webdeveloper answer, as there is no need for additional loop because javascript arrays are working in a way that you only have to define last element

$.views.helpers({
    repeatLoop: function( count ) {
        if (!count) return [];
        var repeat = [];
        repeat[count-1] = {};
        return repeat;
    }
});

And then use as

@{{for ~repeatLoop(10)}}
    {{:#index+1}}
@{{/for}}
3
votes

I am not sure, that JsRender provide this functionality from the box. You can write your own tag, like here: Example Scenario: Creating custom helpers to iterate through fields

$.views.helpers({
    getFields: function( count ) {
        var fieldsArray = [];
        for (var i=0; i < count; i++) {
            fieldsArray.push({});
        }

        return fieldsArray;
    }
});

Demo: http://jsfiddle.net/6UeZC/