0

I'm using express-handlbars as my template engine, and I can use it to place text into my script just fine:

res.render('index', {foo: "something"});

then in my template: var foo = "{{ foo }}"

gives me foo = "something" in my client as I would expect. It works great for strings.

I can't figure out, however, how I can pass an entire object this way?

RedBullet
  • 501
  • 6
  • 18
  • More info in this answer: https://stackoverflow.com/questions/10232574/handlebars-js-parse-object-instead-of-object-object – Jim B. Nov 11 '18 at 22:23

1 Answers1

0

You can pass it using a property like:

const data = { name: 'fooo' }
res.render('index', {foo: "something", data: data });

That way you will acess {{ data.name }}

Or you can pass the object directly

const data = { name: 'fooo' }
res.render('index', data);

and access using {{ name }}

To send the object to a javascript var into client you need to use the JSON.stringify(data)

var object = {{ JSON.stringify(data) }}

Milton Filho
  • 525
  • 3
  • 17
  • Oh, so I would send the stringify and parse in the client? – RedBullet Nov 11 '18 at 23:37
  • Actually if you only stringify it will work, because when the client loads it will be in the correct format. Remind to stringify directly on var, I mean without " like a string value – Milton Filho Nov 11 '18 at 23:39