Handlebars.js parse object instead of [Object object]

前端 未结 5 634
囚心锁ツ
囚心锁ツ 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
    });
    

提交回复
热议问题