Need Handlebars.js to render object data instead of "[Object object]"

108,850

Solution 1

When outputting {{user}}, Handlebars will first retrieve the user's .toString() value. For plain Objects, 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
});

Solution 2

You can simple stringify the JSON:

var user = {}
user = {'id' : 123, 'name' : 'First Name'};
// for print
user.stringify = JSON.stringify(user);

Then in template print by:

{{{user.stringify}}};

Solution 3

I'm using server-side templating in node-js, but this may apply client-side as well. I register Jonathan's json helper in node. In my handler, I add context (such as addressBook) via res.locals. Then I can store the context variable client-side as follows:

<script>
  {{#if addressBook}}
  console.log("addressBook:", {{{json addressBook}}});
  window.addressBook = {{{json addressBook}}};
  {{/if}}
</script>

Note the triple curlies (as pointed out by Jim Liu).

Solution 4

You are trying to pass templating syntax {{ }} inside a JSON object which is not valid.

You may need to do this instead:

myView = new myView({ user : user });

Share:
108,850

Related videos on Youtube

dzm
Author by

dzm

Updated on March 10, 2022

Comments

  • dzm
    dzm about 2 years

    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'.

    • Jonathan Lonowski
      Jonathan Lonowski about 12 years
      You'll have to elaborate on "doesn't work." Can you provide a relevant snippet of code and a description of what you're expecting instead of [Object object]? If you're simply trying to see the object's keys/values, you'll want to use console.log with a debugger or JSON.stringify.
    • dzm
      dzm about 12 years
      Console.log shows [Object object] also. I'll update post to explain better.
  • Jim Liu
    Jim Liu almost 10 years
    it should be: {{{json user}}}, otherwise the json string will be encoded.
  • Oneiros
    Oneiros about 9 years
    Thank you, this is perfect. For Express users: app.set('view engine', 'hbs'); var Handlebars = require('hbs');
  • JayChase
    JayChase over 8 years
    Works great. Also for express-handlebars users: var exphbs = require('express-handlebars'); app.engine('handlebars', exphbs({ helpers: { json: function (context) { return JSON.stringify(context); } } }));
  • Derek Soike
    Derek Soike almost 8 years
    Or just include the helpers when you render. res.render('index', { var1: 'some value', helpers: { json: function (context) { return JSON.stringify(context); } });
  • buycanna.io
    buycanna.io about 6 years
    Worked like a charm! How neat.
  • hazelcodes
    hazelcodes about 6 years
    The answers above are splendid. I actually encountered an issue when rendering the JSON string in the view because i had an unescaped quote, This answer solved that stackoverflow.com/a/22105906/7998284
  • acmoune
    acmoune about 6 years
    What if user is created with new User(...) ? JSON.stringify() will lost all code from the User class/prototype, and leave you with a plain object. How to pass an Object as is ?
  • acmoune
    acmoune about 6 years
    This can be required when you are passing that object (user in this case) to JavaScript...
  • Jonathan Lonowski
    Jonathan Lonowski about 6 years
    @acmoune Going over the network, from server to client, the object has to be serialized into a data format. So sending it as it is in memory isn't strictly possible. Though, you may be able to share the definition of the User type and reconstruct the instance for the client – user : new User({{{json user}}}).
  • acmoune
    acmoune about 6 years
    @JonathanLonowski, You are right, I would have prefer to be able to do var data = JSON.parse({{user}}) or simply var data = {{user}}, but it is just impossible.