简体   繁体   English

需要 Handlebars.js 来渲染 object 数据而不是“[Object object]”

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

I'm using Handlebars templates and JSON data is already represented in [Object object], how do I parse this data outside of the Handlebars?我正在使用 Handlebars 模板,并且 JSON 数据已经在 [Object object] 中表示,如何在 Handlebars 之外解析这些数据? For example, I'm trying to populate a JavaScript variable on the page through a handlebars tag, but this doesn't work.例如,我试图通过把手标签在页面上填充 JavaScript 变量,但这不起作用。

Any suggestions?有什么建议么? Thank you!谢谢!

EDIT:编辑:

To clarify, I'm using ExpressJS w/ Handlebars for templating.为了澄清,我使用 ExpressJS w/ Handlebars 进行模板。 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.然后在我的 index.hbs 模板中,我现在有一个{{user}} object。 I can use {{#each}} to iterate through the object just fine.我可以使用{{#each}}来遍历 object 就好了。 However, I'm also using Backbonejs and I want to pass this data to a View, such as this:但是,我也在使用 Backbonejs,我想将此数据传递给视图,例如:

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'.问题是,如果我将 {{user}} 放入 console.log 中, {{user}}只会在源中显示[Object object] ,我会收到错误消息“意外标识符”。

When outputting {{user}} , Handlebars will first retrieve the user 's .toString() value.输出{{user}} ,Handlebars 将首先检索user.toString()值。 For plain Object s, the default result of this is the "[object Object]" you're seeing.对于普通的Object s,它的默认结果是您看到"[object Object]"

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

You can simple stringify the JSON:您可以简单地将 JSON字符串化

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

Then in template print by:然后在模板中打印:

{{{user.stringify}}};

I'm using server-side templating in node-js, but this may apply client-side as well.我在 node-js 中使用服务器端模板,但这也可能适用于客户端。 I register Jonathan 's json helper in node.我在 node.js 中注册了Jonathan的 json 助手。 In my handler, I add context (such as addressBook) via res.locals.在我的处理程序中,我通过 res.locals 添加上下文(例如 addressBook)。 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 ).注意三重卷曲(正如Jim Liu指出的那样)。

You are trying to pass templating syntax {{ }} inside a JSON object which is not valid.您正在尝试在无效的 JSON 对象中传递模板语法{{ }}

You may need to do this instead:您可能需要这样做:

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

You can render the keys/values of a list or object in a Handlebars template like this:您可以在 Handlebars 模板中呈现列表或 object 的键/值,如下所示:

{{#each the_object}}
  {{@key}}: {{this}}
{{/each}}

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"
    }
  }
}

In the Node Router - Stringify the response object.在节点路由器中 - 字符串化响应对象。 See below line.见下线。

 response.render("view", {responseObject:JSON.stringify(object)});

In HTML Script tag - user Template literals (Template strings) and use JSON.parse.在 HTML Script 标签中 - 用户模板文字(模板字符串)并使用 JSON.parse。

const json= `{{{responseObject}}}`;
const str = JSON.parse(json);

Worked like a charm!像魅力一样工作!

To condense (what I found to be) the most helpful answers...浓缩(我发现是)最有用的答案......

JSON helper for handlebars ( credit ): JSON handlebars助手( 信用):

Handlebars.registerHelper("json", function (context) {
    return JSON.stringify(context);
});

JSON helper for express-handlebars ( credit and I updated to newest conventions): JSON express-handlebars助手( 信用和我更新到最新的约定):

app.engine(
    "handlebars",
    exphbs.engine({
        defaultLayout: "main",
        helpers: {
            json: function (context) { 
                return JSON.stringify(context);
            }
        }
    })
);

And then on the templating side: {{json example}}然后在模板方面: {{json example}}

Just improving the answer from @sajjad.只是改善@sajjad 的答案。

Adding a 'pre' tag will make it look a lot nicer.添加一个'pre'标签会让它看起来好多了。

<pre>
  {{#each the_object}}
    {{@key}}: {{this}}
  {{/each}}
</pre>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM