Trung Tran
Trung Tran

Reputation: 13721

Send handlebars data to client-side javascript

I am building a node.js application and I'm using handlebars. I wanted to check if there's a way for me to send data defined in a handlebars template to client side javascript to be used in calculations. For example, here is my controller:

module.exports = function (req, res) {

    var projectId = req.params.id;
    var context = {
        cost: 500,
        revenue: 1000, 
    }

    res.render('../views/reports', context)
};

On the client-side javascript file, I want to do something like:

$(document).ready(function(context) {
    var profit = context.revenue - context.cost;
});

I'm not sure how to pass the context into the client side javascript.

Can someone help?

Thanks!

Upvotes: 0

Views: 1199

Answers (1)

Will
Will

Reputation: 544

Client

$.post("/endpoint_on_server",
{
    id: "xyz"
},
function(context){ //the result of the res.render
    //update the view
    $('body').html(context);
});

Server

app.post('/endpoint_on_server', function(req, res){
  var projectId = req.params.id; //xyz
  var context = {
    cost: 500,
    revenue: 1000, 
  }

  res.render('../views/reports', context)
}

Upvotes: 1

Related Questions