1

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.

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88
timothy.B
  • 116
  • 6

1 Answers1

2

I think you are going completely in a wrong direction..

  1. What ejs is for?

ejs is javascript embedded in html so you can create dynamic html.

  1. so whatever logic you have just write it inside the ejs template and let it handle everything. you just need to pass the information to ejs engine.

So instead of

if (obj)
            {
                return generatePartial1(data);
            }
            else
            {
                return generatePartial2(data);
            }

I would suggest to capture the whole data

if (obj)
            {
                array1.push(data);
            }
            else
            {
                array2.push(data);
            }
  1. and then pass this whole bunch of data to ejs, write the conditions and all logic in ejs file, and let it handle the html logic. for ex.

res.render('template_file.js', { array1: array1, array2: array2 });

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88