I've started to use NodeJS for a couple of months now and I came across a little problem with partials rendering. I'd like to include a partial view in some templates but I want this partial to be dynamically generated from the server (because it depends on data retrieved from DB and other stuff).
I tried to create a template helper to do that but as the processing needs to be done asynchronously I can't get an html return to write within my template.
Basically what would be the best for me would be something similar to (this code does not work obviously):
template_file.js
...
<div>
<%- generatePartial(data) %>
</div>
...
helper_middleware.js
module.exports = function registerAppHelpers(request, response, next)
{
var appHelpers = {};
appHelpers.generatePartial = function generatePartial(data)
{
if (request.isAuthenticated())
{
DB.findOne({ id: request.user.id }, function found(error, obj)
{
if (error)
...
if (obj)
{
return generatePartial1(data);
}
else
{
return generatePartial2(data);
}
});
}
else
{
return generatePartial3(data);
}
};
// Register the helpers as local variables to be accessed within a template.
for (var helper in appHelpers) {
response.locals[helper] = appHelpers[helper];
}
next();
};
Now I may be completely wrong about the way I want to deal with this problem, so if you have any solution/other suggestions about that do not hesitate.
PS : I use ExpressJS and EJS.