Dan Kanze
Dan Kanze

Reputation: 18595

Iterate through Array of Objects using Dustjs

After a JSONP call I am returned:

[
    {
        "text": "yo whats up?",
        "id": 1
    },
    {
        "text": "hey man!",
        "id": 2
    },
    {
        "text": "dude.",
        "id": 3
    }
]

Heres the actual API call:
http://api.twitter.com/1/statuses/user_timeline/codinghorror.json

Using Dust.js I would do something like:

<ul>
{#myPosts}
  <li>{text}, {id}{~n}</li>
{:else}
  <p>Humm...</p>
{/myPosts}
</ul>

But there is no key "myPosts" in the response. That's the problem. Checkout the API call too see how the JSON is being returned, mabye I'm interpreting this wrong.

What syntax would I use in Dust.js to iterate through each object in this array?

Upvotes: 1

Views: 2881

Answers (2)

Interrobang
Interrobang

Reputation: 17434

You can use the "current context" shortcut.

{#.}
  {text} - {id}<br />
{/.}

Upvotes: 5

Olaf Dietsche
Olaf Dietsche

Reputation: 74048

From dustjs {guide}, I would say, your example should already loop through the array. You just need it as

{
    myPosts: [
        {
            "text": "yo whats up?",
            "id": 1
        },
        {
            "text": "hey man!",
            "id": 2
        },
        {
            "text": "dude.",
            "id": 3
        }
    ]
}

From the Dust Tutorial - Dust under the covers, I've built this JSFiddle. Ignoring the boilerplate, it comes down to prefixing the received JSONP array with myPosts yourself and pass that to dustjs

var jsonp = [...];
dust.render('template', { myPosts: jsonp }, function (err, out) {
...
});

To access anything in your template, you must name it. There is no other way, AFAICS.

Upvotes: 1

Related Questions