limit results of each in handlebars.js

前端 未结 4 989
刺人心
刺人心 2020-12-14 07:29

I have written a small plugin that displays tweets. following is the code that loops and displays the tweets.

    

        
4条回答
  •  情歌与酒
    2020-12-14 08:05

    I think you have two options:

    1. Limit the size of your collection before handing it to Handlebars.
    2. Write your own block helper that lets you specify a limit.

    The actual each implementation is pretty simple so adapting it to include an upper limit is fairly straight forward:

    // Warning: untested code
    Handlebars.registerHelper('each_upto', function(ary, max, options) {
        if(!ary || ary.length == 0)
            return options.inverse(this);
    
        var result = [ ];
        for(var i = 0; i < max && i < ary.length; ++i)
            result.push(options.fn(ary[i]));
        return result.join('');
    });
    

    Then in your template:

    
    

提交回复
热议问题