Handlebars.js parse object instead of [Object object]

前端 未结 5 625
囚心锁ツ
囚心锁ツ 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 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"
        }
      }
    }
    

提交回复
热议问题