简体   繁体   English

如何检查值是否是Handlebars中的对象?

[英]How to check if value is an object in Handlebars?

jsBin Example jsBin例子

Here is my little model: 这是我的小模特:

var stuff = [{
  there: 'blah',
  that: {
    one: 'bbb',
    two: 'ccc'
  }
}];

First, for the following template, I don't understand why the first {{@key}} doesn't output anything and the second one does. 首先,对于以下模板,我不明白为什么第一个{{@key}}不输出任何内容而第二个输出任何内容。

{{#each this}}
  {{@key}}
  {{#each that}}
    {{@key}}
  {{/each}}
{{/each}}

And more importantly I am trying to use this next template and a helper to check if a value is an object or a string and either iterate over it and print the keys, or just print out the key. 更重要的是,我正在尝试使用下一个模板和帮助程序来检查值是对象还是字符串,并迭代它并打印键,或者只打印出键。

{{#each this}}
  {{#if isObj this}}
    {{#each that}}
      {{@key}}
    {{/each}}
  {{else}}
    {{@key}}
  {{/if}}
{{/each}}

Helper: 帮手:

Handlebars.registerHelper('isObj', function(thing) {
  return $.type(thing) === 'object';
});

The first one I can answer, you should use {{@index}} instead of {{@key}} because your iterating an array. 我可以回答第一个问题,你应该使用{{@index}}而不是{{@key}}因为你在迭代一个数组。 I'm looking into the second one. 我正在研究第二个问题。

A: A:

{{#each this}}
  key: {{@index}}
  {{#each that}}
    key1: {{@key}}
  {{/each}}
{{/each}}

For part b it seems you're going to have to register a new helper function as if cant take the return from another funciton. 对于b部分,似乎你必须注册一个新的辅助函数,好像不能从另一个函数返回。 You're block helper will be something like ( pretty much stole this from here ): 你是块帮手会是这样的( 几乎从这里偷走了这个 ):

Handlebars.registerHelper('ifObject', function(item, options) {
  if(typeof item === "object") {
    return options.fn(this);
  } else {
    return options.inverse(this);
  }
});

Now change your template to something like: 现在将模板更改为:

{{#each this}}
  {{#ifObject this}}
    {{#each that}}
      {{@key}}
    {{/each}}
  {{else}}
    {{@key}}
  {{/ifObject}}
{{/each}}

This was working on tryhandlebars.com and updated your jsbin , hope it helps! 这是在tryhandlebars.com上工作并更新你的jsbin ,希望它有所帮助!

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

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