Question

I have this small dust template:

    <div id="post-list">
        <h1>Posts</h1>
        {#posts}
            <h4><a href="{url}">{title}</a></h4>
            <p>by {author} on {date}</p>
            <p>{content}</p>
        {/posts}
    </div>

and I'm trying to get the posts asynchronously from a postgresql database on rendering:

var data = {posts: 
        function(chunk, context, bodies) {
            return chunk.map(function(chunk) {                                            
                client.query("select * from blogposts", function (err, resultPosts) {
                    if (err) throw err;
                    return chunk.render(bodies.block, context.push(resultPosts.rows)).end();
                });                                   
            });
        }
}

Unfortunately this does not work. The only thing the template renders is by on.

How can I fix this? Thanks.

EDIT: Setting the chunk.render line to:

return chunk.render(bodies.block, context.push(resultPosts.rows[0])).end();

Works in showing me the first post in the resultPosts list. But I really need to render the entire list.

Was it helpful?

Solution

Well it turns out I have to loop over my query rows and write each chunk piece by piece. I don't know if there is any better way to do this:

var data = {posts: 
        function(chunk, context, bodies) {
            return chunk.map(function(chunk) {                                            
                client.query("select * from blogposts", function (err, resultPosts) {
                    if (err) throw err;
                    for (index=0; index<resultPosts.rows.length; index++) {
                        chunk.render(bodies.block, context.push(resultPosts.rows[index]));
                    };
                    return chunk.end();
                });                                   
            });
        }
}

OTHER TIPS

You might be able to render the list by putting the items inside a {#.} {/.} block like this:

<div id="post-list">
        <h1>Posts</h1>
        {#posts}
            {#.}
               <h4><a href="{url}">{title}</a></h4>
               <p>by {author} on {date}</p>
               <p>{content}</p>
            {/.}
        {/posts}
</div>

Sometimes I have a situation where I can't access the object's or array's items unless I wrap the template inside with {#.}{/.}.

The correct way to do iteration implicitly is to use chunk.section instead of chunk.render. Then you can skip doing the iteration yourself.

return chunk.map(function(chunk) {
  client.query("select * from blogposts", function(err, resultPosts) {
    if (err) throw err;
    return chunk.section(resultPosts.rows, context, bodies).end();
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top