NakedWarrior NakedWarrior - 6 months ago 56
Node.js Question

How to fill data into ejs view and return a string is pure html with expressjs

I have a ejs view like this

<p>
<%= user.firstName %> <%= user.lastName %>
</p>


and in my controller I want to do something like this

var html = fill('ejs-template', data);
res.send(JSON.stringify(html))


then I can use the html with data content to do something else

Answer

The quickest way, since you're using Express:

res.render('ejs-template', data, function(err, html) {
  if (err) return res.sendStatus(500);
  ...do something with the HTML...
});

If you don't necessarily want to use Express, you can use the ejs module directly:

var ejs = require('ejs');
ejs.renderFile('./views/ejs-template.ejs', data, options, function(err, html) {
  ...
});

More info here.