2
votes

I know {{for}} can loop through a collection. But can I loop based on the total number?

Say, if I have a TotalPage which is an integer, how can I create a paging list like:

{{for (Page=1; Page<=TotalPage; Page++;)}} // I made up this statement.
    {{if Page=CurrentPage}}
        <li class="selected">{{>Page}}</li>
    {{else}}
        <li>{{>Page}}</li>
    {{/if}}
{{/for}}

Is that possible in jsRender?

2
My gut says that, if you want to do this, you're putting too much logic (which belongs in a controller) into the view. - Matt Ball
Then, should I pass in an array or something that contains [1, 2, 3... , TotalPage] into the template? What is the best way to construct a pager in the template? - Blaise
I'd think the best way to do it would be to pass in an object containing the information so the template can render it with little to no logic. I try to limit the logic in my templates to checking if an object exists or is set to a certain value before rendering a section. Much more than that and the logic goes in the code that creates the object to be rendered. - MrOBrian

2 Answers

2
votes

This can be accomplished with the #index attribute that exists within the {{for /}} block.

{{for myModel.myArray }}
    <li>This is item number {{:#index}}</li>
{{/for}}

#index contains the current index of the array being rendered. You cannot, however, at least natively, specify an arbitrary number of times to render a template. as Matt Ball says in the comments, that's too much logic to be putting in a template.

But if you're that determined, you can create an array in your model with an arbitrary size and iterate over that.

0
votes
       {{for #data.pages}}
          {{if #data.page == currentPage }}  // data refers to the pages 
              <li class="selected">{{>Page}}</li>
          {{/if}}   
        {{else}}
               <li>{{>Page}}</li>   
        {{/for}}

Hope this is the structure that you are looking for ,