如何将参数传递给Handlebars帮助器?options.hash和options.data之间有什么区别

wry*_*ych 14 handlebars.js ember.js

这是一个典型的Handlebars助手:

Ember.Handlebars.helper 'myHelper', (value, options) ->
  ...
Run Code Online (Sandbox Code Playgroud)

根据这个protip,你可以将哈希传递给Handlebars助手.我查看了源代码,发现它提供了两者options.hashoptions.data.我有点困惑,因为这不会按预期工作:

{{#with controllers.currentCardCategory}}
  {{#each property in cardProperties}}
    <td class="td">{{cardProperty this property=property.symbol}}</td> 
  {{/each}}
{{/with}}
Run Code Online (Sandbox Code Playgroud)

this是目前的Card记录.在这里,我得到了property.symbol字符串

但这有效:

{{#with controllers.currentCardCategory}}
  {{#each property in cardProperties}}
    <td class="td">{{cardProperty this property.symbol}}</td> 
  {{/each}}
{{/with}}
Run Code Online (Sandbox Code Playgroud)

并且价值可以通过options.

但现在我不能这样做:

{{#with controllers.currentCardCategory}}
  {{#each property in cardProperties}}
    <td class="td">{{cardProperty this property.symbol anotherParam yetAnotherParam}}</td> 
  {{/each}}
{{/with}}
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何传递等参数,以辅助什么之间的区别options.hash,并options.data在助手

Dar*_*kar 16

传递给助手的参数变为arguments辅助函数.您在{{helperName成为参数后立即在模板中提供的值.传递给帮助程序的最后一个参数是一个options对象,它为辅助程序提供附加信息,例如,options.hashoptions.contexts等.参数对应于options.hash属性后提供的键值对.

对于一个带有hello3个参数的帮助器,帮助器将是,

Ember.Handlebars.helper('hello', function(a, b, c, options) {
  return '%@ - %@ - %@'.fmt(a, b, c);
});
Run Code Online (Sandbox Code Playgroud)

hello助手可以在模板中使用像这样,

{{hello lorem ipsum dolor}}
Run Code Online (Sandbox Code Playgroud)

这里将使用,和属性的值lorem,并将其作为组合字符串返回.ipsumdolor

除了必需的参数之外,如果你传入附加参数,它们将可用options.hash.这些属性被视为字符串,默认情况下不会解析.您需要先使用,options.data.view查找其值.如果需要,请参阅此答案以获取示例.

最后options.data是为帮助者提供的特殊财产.它Frame是包含变量,上下文等的原始把手.它主要用于块助手.由于块助手不会自己渲染而是调用其他助手,因此options.data允许这样的块助手将其他变量注入子助手帧.有关详细信息,请参阅此处的文档.

这是一个jsbin的例子.