从 Handlebars Helper 返回对象数组

jas*_*tco 1 arrays templating node.js handlebars.js

我正在尝试编写一个助手,它将返回一个可以循环的对象数组。这是我现在所拥有的:

Handlebars.registerHelper('testHelper', () => {
  return [
    { slug: 'Test', title: 'This is it!' },
    { slug: 'Test 2', title: 'This is the second it!' },
  ];
});
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

{{#entries this}}
  <a href="/{{slug}}">{{title}}</a>
{{/entries}}
Run Code Online (Sandbox Code Playgroud)

我正在收到[object, Object]数组中的每个对象而不是单个值。请帮忙 :)

谢谢!

ras*_*ter 6

Handlebars 中助手的工作方式有点棘手。您无需将数据从助手传递到主模板主体,而是将模板主体中与助手相关的部分传递给助手。

因此,例如,当您执行以下操作时:

{{#entries this}}
  <a href="/{{slug}}">{{title}}</a>
{{/entries}}
Run Code Online (Sandbox Code Playgroud)

您向助手提供两件事entries:1)当前上下文(this)2)要应用的一些模板逻辑

以下是助手如何获取这些物品:

Handlebars.registerHelper('entries', (data, options) => {
  // data is whatever was provided as a parameter from caller
  // options is an object provided by handlebars that includes a function 'fn'
  //   that we can invoke to apply the template enclosed between 
  //   #entries and /entries from the main template
   :
   :
});
Run Code Online (Sandbox Code Playgroud)

所以,要做你想做的事:

Handlebars.registerHelper('testHelper', (ignore, opt) => {
  var data = [
    { slug: 'Test', title: 'This is it!' },
    { slug: 'Test 2', title: 'This is the second it!' },
  ];
  var results = '';
  data.forEach( (item) => {
    results += opt.fn(item);
  });
  return results;
});
Run Code Online (Sandbox Code Playgroud)

应用opt.fn(item)模板的这一部分:

<a href="/{{slug}}">{{title}}</a>

这个想法是创建一个字符串(html 的一部分),然后返回该字符串并将其放入由主模板制定的字符串中。

这是一个展示此工作原理的示例。

{{#entries this}}
  <a href="/{{slug}}">{{title}}</a>
{{/entries}}
Run Code Online (Sandbox Code Playgroud)

让我也回应其他人一直试图告诉你的话。尝试在模板中填充数据没有多大意义。这应该作为模板的上下文传递以进行操作。否则,您会将业务逻辑与模板逻辑(视图)混合在一起,这会不必要地使事情变得复杂。

您可以在同一代码段中进行以下简单更改,将数据传递到模板:

Handlebars.registerHelper('entries', (data, options) => {
  // data is whatever was provided as a parameter from caller
  // options is an object provided by handlebars that includes a function 'fn'
  //   that we can invoke to apply the template enclosed between 
  //   #entries and /entries from the main template
   :
   :
});
Run Code Online (Sandbox Code Playgroud)

这样您就可以在 JavaScript 中检索数据并保留模板的预期用途 - 制定 html。