Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from server code to ejs template?

I have a simple server and and I get the data on url through browser perfectly. I am trying to get the data in my ejs template.

This is how I am getting the data:

app.get('/some', function(req, res, next) {
var size = 3;
var curr = req.query.page || 1;

var allSome = Object.assign([], jsFile.some);
some = allSome.slice((curr - 1) * size, curr * size);

some = some.map(function(som) {
    var mapSome = Object.assign({}, som);
    delete mapSome.var1;
    delete mapSome.var2;
    return mapSome;
});

return res.json({
    some: some,
    total: allSome.length,
});
});

This is how I am trying to pass the data:

app.get('/some', function (req, res, next) {
    res.render('events', {data : res.json.some});
});

This is how I am trying to get the data:

<ul>
    <% data.forEach(function(dat) { %>
    <li><%= dat.var3 %></li>
    <li><%= dat.var4%>
    <% }); %>
</ul>

But I am getting:

Cannot read property 'forEach' of undefined

I am new to ejs and front end. I would really appreciate if someone could help me in this.

like image 249
Panda Avatar asked Jan 24 '26 12:01

Panda


1 Answers

This block of code will repond with json not pass it to next middleware

return res.json({
  some: some,
  total: allSome.length,
});

Replacing the above block with the following should do:

res.render('events', {data : some});
like image 131
1565986223 Avatar answered Jan 26 '26 02:01

1565986223