Search code examples
ractivejs

How to loop in ractive.js


I have got the following data (sample):

"data": {
        "eventsHeading": "Upcoming events",
        "eventsToBeDisplayed": 3,
        "allEventLinkText": "See all events",
        "eventsList": [
    {
        "eventDate": "22/12/2015",
        "eventTitle": "EVENT INFO 1"
    },
    {
        "eventDate": "22/12/2015",
        "eventTitle": "EVENT INFO 2"
    },
    {
        "eventDate": "14/01/2016",
        "eventTitle": "EVENT INFO 3"
    },
    {
        "eventDate": "14/01/2016",
        "eventTitle": "EVENT INFO 4"
    }
        ]
    }

And I have something like this:

{{#eventsList}}
    <tr>
        <td class="date-column">{{eventDate}}</td>
        <td class="text-link truncate-text"><span decorator="tooltip:{{eventTitle}}" tabindex="0">{{eventTitle}}</span>
    </tr>
{{/}}

And now it will just print all the data for eventList. What I want to do is add a for loop like

i=0;i<={{eventsToBeDisplayed}};i++

so only 3 of the data will show.

What do you think is the best approach for this?


Solution

  • You can add an indexer to the loop and then conditionally filter inside the loop:

    {{#eventsList:i}}
        {{# i < eventsToDisplay}}
        <tr>
            <td class="date-column">{{eventDate}}</td>
            <td class="text-link truncate-text"><span decorator="tooltip:{{eventTitle}}" tabindex="0">{{eventTitle}}</span>
        </tr>
        {{/}}
    {{/}}