3

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!

Trung Tran
  • 11,579
  • 39
  • 105
  • 187

4 Answers4

2

You can pass data using JSON.Stringify() with {{{ }}}

There is Two Example

  1. use Stringify on render function
    • server
return res.render('../views/person', {person : JSON.Stringify(person)});
  • client
var person = {{{person}}}
console.log(person)
  1. Makes HBS Helper
    • server
hbs.hbs.registerHelper('convert', function (date) {
        if (!date) {
            return;
        }
        return JSON.stringify(date);
    });

return res.render('../views/person', {person : person});
  • client
var person = {{{convert person}}}
console.log(person)

I suggest number 2. It can be use on HTML and also Client javascript.

jinseok.oh
  • 189
  • 1
  • 7
  • 1
    I've tried the number 2 solution, but when my page loads I get `Uncaught SyntaxError: Unexpected token '{'`. This client side javascript is not understanding the triple brackets. How are you making this work? – Matthew Wolman Apr 29 '20 at 20:39
  • 1
    triple brackets only can use in .hbs files. – jinseok.oh Dec 16 '20 at 04:31
  • Matthew Wolman // you should declare javascript variable which contain triple brackets. and pass to javascript file that variable – jinseok.oh Dec 16 '20 at 04:33
1

try this

 res.render('../views/person', {person: person})
keja
  • 1,228
  • 1
  • 16
  • 18
  • if you want to use it in a external js file, you need to define the variable "person" before you access it from your js file, or retrieve it with ajax into you js file (like Kevin wrote etc). or if you wanna use it in handlebar file write the console.log within a script tag – keja Jan 25 '16 at 16:38
  • 1
    oh handlebars escapes the output, but you can fix it like this: http://stackoverflow.com/a/10233247/3774580 – keja Jan 25 '16 at 16:43
1

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
})
Kevin Hernandez
  • 513
  • 1
  • 6
  • 20
  • Thanks - would the `http.get({})...` be in the client.js file? – Trung Tran Jan 25 '16 at 16:31
  • Yeah. The client is making a "GET" http request to a specific location on the server, which is served by Express. Whatever you serve, it gets handled in the server.js file, and can even be tested in the browser if you go to that route "localhost:8080/person/a". Likewise, if you want to send data to the server, have your client send a "POST" http request and make sure that your server accepts POST requests to a specific route like "localhost:8080/send/person/". Just take a look at the 2 links I provided for how to do this. – Kevin Hernandez Jan 25 '16 at 16:42
0

your route in the server could be like this

app.get("/",(req,res)=>{
  res.render("view_name",{val: 123,val2: "123"});
 });

then in your view file you could do something like this:

<script>
  console.log({{val}}); // if value it's number type
  console.log("{{val2}}");//in quotes if it's string type
  const val1 = {{val}};  
  const val2 = "{{val1}}";
<script/>
daniloll
  • 1
  • 1