Search code examples
javascriptnode.jsdust.js

dust.js templates: How to render a section asynchronously?


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.


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();
                    });                                   
                });
            }
    }