0

Possible Duplicate:
Custom for-loop helper for EmberJS/HandlebarsJS

I use Handlebars for a website and I have an important question :

Sometimes you give to your template a full array and you just want to show the n first element... how do you do that with handlebars? I can't find...

Community
  • 1
  • 1
stadja
  • 56
  • 6
  • We can't use the Simple iterator example from http://handlebarsjs.com/block_helpers.html because I use an ArrayController that is filled later on and this function doesn't update when something change. – stadja Nov 01 '12 at 10:44

1 Answers1

0

Here is how I did it (and it works !!!)

First, i had in my model a 'preview' property/function, that just return the arrayController in an array :

objectToLoop = Ember.Object.extend({ 
        ...
    arrayController: [],
    preview: function() {
        return this.get('arrayController').toArray();
    }.property('arrayController.@each'),
        ...
});

Then, I add a new Handlebars helper :

Handlebars.registerHelper("for", function forLoop(arrayToLoop, options) {
    var data = Ember.Handlebars.get(this, arrayToLoop, options.fn);

    if (data.length == 0) {
        return 'Chargement...';
    }

    filtered = data.slice(options.hash.start || 0, options.hash.end || data.length);

    var ret = "";
    for(var i=0; i< filtered.length; i++) {
        ret = ret + options.fn(filtered[i]);
    }
    return ret;     
});

And thanks to all this magic, I can then call it in my view :

<script type="text/x-handlebars"> 
    <ul>
        {{#bind objectToLoop.preview}}
            {{#for this end=4}}
                <li>{{{someProperty}}}</li>
            {{/for}}
        {{/bind}}
    </ul>
</script>

And that's it.

I know it is not optimal, so whoever have an idea on how to improve it, PLEASE, make me know :)

stadja
  • 56
  • 6