node.jsexpresshandlebars.jsexpress-handlebars

express handlebars render to string instead of response


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?


Solution

  • 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} );
       });
    });