Search code examples
javascriptractivejs

Ractive.js template looping


I'm making an ajax call and pull down the total number of pages:

$.get(path, function( data ) {
    ractive.set({
    'articles' : data.articles,
    'totalpages' : data.totalpages
    });
});

Is there any way I can render the pagination buttons from the total page count? Something like (assuming totalpages = 4):

{{#if loop totalpages times:num}}
  <a href="#">{{num}}</a> | 
{{/if}}

Would output

<a href="#">1</a> | <a href="#">2</a> | <a href="#">3</a> | <a href="#">4</a>

I had a look at Mustache docs, but Mustache isn't quite the same.

Thanks, Rob


Solution

  • Use a computed property in your component or ractive instance:

    computed: {
        total: 'new Array(${totalPages})'               
    }
    

    And then use the :index (or whatever you want) to alias the index on the each:

    {{#each total:index}}
    <a href="#">{{index+1}}</a>
    {{/each}}
    

    Edit: Above total computed property is Ractive shorthand for:

    computed: {
        total: function(){
            return new Array(this.get('totalPages'));
        }   
    }