5

I currently use express handlebars successfully - however I want to use it for updating and rendering only a piece of a page - a list of items that changes over time, so I want to update just that list on a timer. Essentially on the browser I have the following code:

$.get( "myUrl").then( result => $("#targetdiv").html( result.html ));

so on the server for every page I've been doing something like this:

app.get("/myUrl", async (req, res) => {res.render( "someTemplateFile");} )

however, clearly those two don't work together - I need do so something like this:

app.get("/myUrl", async (req, response) => 
{
   var renderedHtml =   .....someCodeHere...... ("someTemplateFile");
   response.send( {html:renderedHtml} );
}

Is there an easy way of doing that?

Darren Oakey
  • 2,894
  • 3
  • 29
  • 55
  • `res.render` does the same thing - it creates HTML and sends to browser. Why do you say "they don't work together"? – Vasan May 16 '18 at 02:30
  • I guess I wanted it as json - I've had security problems trying to return html as html before from jquery ajax type functions - but json always seems to work. – Darren Oakey May 16 '18 at 02:49

2 Answers2

3

Use the render API like this:

var hb = require('express-handlebars').create();
app.get("/myUrl", async (req, response) => 
{
   hb.render("some.hbs",{title:"Title",body:"Body"}).then((renderedHtml) => {
       response.send( {html:renderedHtml} );
   });
});
Vasan
  • 4,810
  • 4
  • 20
  • 39
1
app.get("/myUrl", (req, res) => {
  res.render(
    'template',
    dataObject,
    (err, rawHtml) => {
      if(!err) {
        console.log(rawHtml)
        res.send(rawHtml)
      }
    }
  )
})
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
rabie jegham
  • 125
  • 2
  • 3