Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

jquery - limit results of each in handlebars.js

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

    <script id="tweets-template" type="text/x-handlebars-template" >
        {{#each this}}
        <li>
        <p>{{tweet}}</p>
            <span id="author">{{author}}<span/>
        </li>
        {{/each}}
    </script>

But what I want to do is limit the number of tweets to 5 or 10. But the loop is listing all the available tweets. How do I limit the tweets like in for loop. like

    for(i=0;i<5;i++){display the tweets}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

<script id="tweets-template" type="text/x-handlebars-template" >
    {{#each_upto this 5}}
        <li>
            <p>{{tweet}}</p>
            <span id="author">{{author}}<span/>
        </li>
    {{/each_upto}}
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...