Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render an inline template a fixed number of times

I have a search results screen and in the results payload supplied I get a pageCount number back. With this, I intend to create a simple pager.

So really I need to do this:

    <!-- ko for(var i = 0; i < pageCount(); i++) -->
        <div data-bind="html: 'Page '+$index()"></div>
    <!-- /ko -->

Obviously this doesn't work, but you get what I mean. I suppose I could create another observableArray of integers on the View Model with each item representing a page, but this seems like overkill. However, it may be my only option?!

Oh well, I thought I'd better ask, as sometimes there's some killer function which creates a range on the fly and then I can foreach over that bad boy.

Anyhooo, I think you see what I mean. thanks

like image 456
krisdyson Avatar asked Dec 06 '22 13:12

krisdyson


2 Answers

I would use foreach: new Array(pageCount()):

<!-- ko foreach: new Array(pageCount())  -->
        <div data-bind="html: 'Page '+$index()"></div>
<!-- /ko -->​
like image 156
antishok Avatar answered Apr 02 '23 21:04

antishok


If I understand your requirements correctly, take a look at Michael Best's 'Repeat' plugin:

https://github.com/mbest/knockout-repeat

Example:

<div data-bind="repeat: pageCount" data-repeat-bind="html: 'Page '+$index"></div>
like image 27
John Earles Avatar answered Apr 02 '23 21:04

John Earles