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?
4
votes
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;
}
});
<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