I'm using Handlebars templates and JSON data is already represented in [Object object], how do I parse this data outside of the Handlebars? For example, I'm trying to populate a JavaScript variable on the page through a handlebars tag, but this doesn't work.
Any suggestions? Thank you!
EDIT:
To clarify, I'm using ExpressJS w/ Handlebars for templating. In my route, I have this:
var user = {} user = {'id' : 123, 'name' : 'First Name'} res.render('index', {user : user});
Then in my index.hbs template, I now have a {{user}}
object. I can use {{#each}}
to iterate through the object just fine. However, I'm also using Backbonejs and I want to pass this data to a View, such as this:
myView = new myView({user : {{user}});
The problem, is that {{user}}
simply shows [Object object]
in the source if I put it in console.log I get an error, 'Unexpected Identifier'.
Handlebars. js is a Javascript library used to create reusable webpage templates. The templates are combination of HTML, text, and expressions. The expressions are included in the html document and surrounded by double curly braces.
Handlebars. js is a templating engine similar to the ejs module in node. js, but more powerful and simple to use. It ensures minimum templating and is a logicless engine that keeps the view and the code separated.
js or <script> tag or anywhere else, you need to have access to Handlebars object, since you are invoking registerHelper method on that object (which injects a helper into that object). After Handlebars has been modified, every module referencing that object will have access to the new helper.
When outputting {{user}}
, Handlebars will first retrieve the user
's .toString()
value. For plain Object
s, the default result of this is the "[object Object]"
you're seeing.
To get something more useful, you'll either want to display a specific property of the object:
{{user.id}} {{user.name}}
Or, you can use/define a helper to format the object differently:
Handlebars.registerHelper('json', function(context) { return JSON.stringify(context); });
myView = new myView({ user : {{{json user}}} // note triple brackets to disable HTML encoding });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With