Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass handlebars variable to client js file

I'm building an app using node.js + express + handlebars and was looking for a way i can pass handlebars data from the server to client-side javascript files. For example:

//server.js

var person = {
    name: George,
    age: 32, 
}

res.render('../views/person', person)

I want to be able to use the person object on the client side such as:

//client.js

console.log(person.age);
console.log(person.name);

Can someone help?

Thanks!

like image 709
Trung Tran Avatar asked Apr 10 '26 10:04

Trung Tran


2 Answers

try this

 res.render('../views/person', {person: person})
like image 118
keja Avatar answered Apr 11 '26 23:04

keja


If you're passing more than just a few objects, I would recommend building some sort of API around your client-server relationships using Express's routing ( http://expressjs.com/en/guide/routing.html )

// server
app.get('/person/a', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send({person: {age: 30, name: "Bob", greeting: "hello"}});
});

and your client would then call those routes with the http module ( https://nodejs.org/api/http.html ):

// client
http.get({
  hostname: 'localhost',
  port: 80,
  path: 'person/a',
}, (res) => {
// Do stuff with response
})
like image 42
Kevin Hernandez Avatar answered Apr 11 '26 22:04

Kevin Hernandez