how to pass parameters to Handlebars helper? What's the difference between options.hash & options.data

我的未来我决定 提交于 2019-12-03 10:45:34
Darshan Sawardekar

Parameters passed to a helper become arguments to the helper function. The values you provide in the template immediately after the {{helperName become the arguments. The last argument passed to the helper is an options object that provides additional information to helper like, an options.hash and options.contexts, etc. Key value pairs provided after the parameters correspond to the options.hash property.

For a hello helper that takes 3 arguments, the helper would be,

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

The hello helper can be used in a template like so,

{{hello lorem ipsum dolor}}

Here the values of lorem, ipsum, and dolor properties would be used and returned as a combined string.

In addition to the required arguments, if you pass in additonal parameters they would be available in options.hash. These properties are treated as strings and aren't resolved by default. You would need to use, options.data.view to lookup their values first. See this answer for an example if you need to do this.

Finally options.data is special property provided to helpers. It's the raw handlebars Frame that holds variables, contexts and so on. It is mostly for use with block helpers. Since block helpers don't do rendering themselves but call other helpers, options.data allows such block helpers to inject additional variables into the child helpers frame. For details see the docs here.

Here's a jsbin example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!