Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render view into a variable in ExpressJS (for AJAX response)

I want to load the contents of a partial view (written in Jade) into a Bootstrap modal dialog. For this, I use an AJAX call. I could return only the generated HTML and load it into the modal, but there's additional data I need to get along with the rendered view. I would like to be able to return an object like this (parsed to JSON) :

response = {
  some_data: 'blablabla',
  some_more_data: [5, 8, 10, 67],
  my_html: '<div>HTML rendered from the Jade template</div>'
};

Is there a way to do this? For now I can return the rendered HTML like this :

res.render('employees', {layout: false});

But how can I store it in a variable to return along with more data, without having to do more AJAX calls?

like image 484
Samuel Bolduc Avatar asked Aug 05 '13 19:08

Samuel Bolduc


1 Answers

In express you can use app.render with a callback to render a view and get the html:

app.render('employees', {layout: false}, function(err, html){
  var response = {
    some_data: 'blablabla',
    some_more_data: [5, 8, 10, 67],
    my_html: html
  };
  res.send(response);
});
like image 147
mr.freeze Avatar answered Oct 23 '22 03:10

mr.freeze