質問

I have a hard time understanding how to pass an object fetched from a database to a dust.js template.

Let's say I have a template:

{#person}
{name} - {title}
{/person}

I try to setup a context something like this:

var ctx = {
     person: return chunk.map(function(chunk) {
         database.person(12345, function(data) {
            dust.nextTick(function() {
                    chunk.end(data); // What to really do here?
            });
         });
    });
}

Where database.person fetches the object from a database and passes it to a callback.

And then I would run the render function:

res.render('person', ctx);
役に立ちましたか?

解決

The correct form was:

var ctx = {
    person: function(chunk, context, bodies) {
        return chunk.map(function(chunk) {
            database.person(1234, function(data) {
                return chunk.render(bodies.block, context.push(data)).end();
            });
        });
    }
}

Instead of write I had to call render as in Alan's answer.

The whole db call had to be enclosed in the return chunk.map call to work. I also had to chain an end command to send the results back to the stream.

Why these calls are needed is told in the dust.js guide (http://akdubya.github.io/dustjs/#guide):

chunk.map tells Dust to manufacture a new chunk, reserving a slot in the output stream before continuing on to render the rest of the template. You must (eventually) call chunk.end() on a mapped chunk to weave its content back into the stream.

This is something that isn't addressed in the LinkedIn guide pages.

他のヒント

I'm assuming your db call will return something along the lines of a json object such as the "data" below.

The async code looks ok. chunk.write will just write out whatever you give it so you need to pass your data in on the context so it can be accessed in the template. Use chunk.render instead of write. A non-async example would be :

{
    "person": function(chunk, context, bodies) {
        var data = {name:"Smith", title:"Mr"};
        return chunk.render(bodies.block, context.push(data));
    }
}

Running that through linkedin dust tests seems to get the right answer.

Hope that helps, Alan

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top