Handlebars.js parse object instead of [Object object]

前端 未结 5 603
囚心锁ツ
囚心锁ツ 2020-11-27 16:20

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 popu

相关标签:
5条回答
  • 2020-11-27 16:46

    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
    });
    
    0 讨论(0)
  • 2020-11-27 16:51

    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}}};
    
    0 讨论(0)
  • 2020-11-27 16:58

    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 });

    0 讨论(0)
  • 2020-11-27 17:05

    If you want more control over the output formatting you can write your own helper. This one has a recursive function to traverse nested objects.

      Handlebars.registerHelper('objToList', function(context) {
        function toList(obj, indent) {
          var res=""
          for (var k in obj) { 
              if (obj[k] instanceof Object) {
                  res=res+k+"\n"+toList(obj[k], ("   " + indent)) ;
              }
              else{
                  res=res+indent+k+" : "+obj[k]+"\n";
              }
          }
          return res;
        }    
        return toList(context,"");
      });
    

    We used handlebars for email templates and this proved useful for a user like the following

    {
      "user": {
        "id": 123,
        "name": "First Name",
        "account": {
          "bank": "Wells Fargo",
          "sort code": " 123-456"
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-27 17:06

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

    0 讨论(0)
提交回复
热议问题