从数组输出键?

时间:2016-11-08 14:34:26

标签: javascript handlebars.js yaml

如何输出下面的人名?例如马丁和塔比莎?

people:
-  martin:
    job: Developer
    skills:
      - python
      - perl
      - pascal
-  tabitha:
    job: Developer
    skills:
      - lisp
      - fortran
      - erlang

这是循环:

{{#each people}}
    {{ this }}
{{/each}}

2 个答案:

答案 0 :(得分:1)

我找到了答案:

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

答案 1 :(得分:0)

您可以创建一个块助手list来迭代people并使用当前index作为私有变量来获取该对象中第一个键的名称:{{ 1}}。

代码:

Object.keys(context[i])[0]
var people = [{"martin": {"job": "Developer","skills": ["python","perl","pascal"]}}, {"tabitha": {"job": "Developer","skills": ["lisp","fortran","erlang"]}}];

// Register list helper
Handlebars.registerHelper('list', function (context, options) {
  var out = '<ul>',
      data;

  if (options.data) {
    data = Handlebars.createFrame(options.data);
  }

  for (var i = 0, l = context.length; i < l; i++) {
    if (data) {
      data.index = Object.keys(context[i])[0];
    }

    out += '<li>' + options.fn(context[i], {
      data: data
    }) + '</li>';
  }

  out += '</ul>';
  return out;
});

// The main template
var main = Handlebars.compile($('#main').html());

// Register the list partial that 'main' uses
Handlebars.registerPartial('list', $('#list').html());

// Render the list
$('#output').html(main({
  people: people
}));

注意:我已将yaml转换为代码示例的数组。