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...


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 :)

4

1 回答 1

0

这是我的做法(它有效!!!)

首先,我在我的模型中有一个“预览”属性/函数,它只在数组中返回 arrayController:

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

然后,我添加了一个新的 Handlebars 助手:

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;     
});

多亏了所有这些魔法,我可以在我看来这样称呼它:

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

就是这样。

我知道这不是最佳的,所以谁知道如何改进它,请告诉我:)

于 2012-10-31T17:20:29.510 回答