Pergunta

I am using Handlebars.js as js templates. And I need to iterate through the array but not until the array will finish, but less than specific number of times.

So suppose I have a following JSON:

{
    "obj":
        [
            {"user": "Fred", "age": "23", "type": "personal"},
            {"user": "Ralph", "age": "32", "type": "business"},
            {"user": "John", "age": "44", "type": "other"},
            {"user": "Alex", "age": "44", "type": "other"},
            {"user": "Stan", "age": "6", "type": "other"},
            {"user": "Cartman", "age": "5", "type": "other"},
            {"user": "Kennie", "age": "6", "type": "other"}
        ]
}

But I need to output only first 4 users, so Stan, Cartman and Kennie will not be there. If I would need to iterate everything I would use something like this:

<ul>
    {{#each obj}}
    <li>
        <div>{{this.user}}</div>
        <div>{{this.age}}</div>
        <div>{{this.type}}</div>
    </li>
    {{/each}}
</ul>

How can I modify it?

Question 2: Currently I am using obj only for the reason, that I was not able to figure out how to iterate JSON which consists only from array:

        [
            {"user": "Fred", "age": "23", "type": "personal"},
            {"user": "Ralph", "age": "32", "type": "business"}
        ]

How can I change my template to iterate without that pesky obj?

Foi útil?

Solução

Ok I figured out the way to solve question 2:

Using this solves the problem

<ul>
    {{#each this}}
    <li>
        <div>{{this.user}}</div>
        <div>{{this.age}}</div>
        <div>{{this.type}}</div>
    </li>
    {{/each}}
</ul>

As for the first question, apparently there is no way to do this natively with handlebar.js so I am thinking how to write my own Helper for this.

PS. Thanks to mu is too short for showing the answer for the first part: limit results of each in handlebars.js

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top