[英]Handlebar helper inside {{#each}}
I try to call a registered handlebar helper inside a {{#each}}
loop. 我尝试在
{{#each}}
循环中调用已注册的车把助手。 Unfortunately Ember.js complains because it tries to resolve the helper as a property of the controller rather than a helper. 不幸的是,Ember.js抱怨是因为它试图将助手解析为控制器的属性而不是助手。
Handlebars.registerHelper('testHelper', function(name) {
return 'foo: ' + name
});
(names and content are just dummy values to show the example) (名称和内容只是显示示例的虚拟值)
{{#each entry in App.testController}}
<div>{{{testHelper entry.name}}}</div>
{{/each}}
The error that the Ember.js prints is: Ember.js打印的错误是:
Uncaught Error: Handlebars error: Could not find property 'testHelper' on object <App.testController:ember254>.
How do I need to call the registered helper so that it gets recognized? 我如何调用已注册的助手以便识别它?
Got it running, either with this solution , 使用此解决方案 ,让它运行
Javascript 使用Javascript
Handlebars.registerHelper('testHelper', function(property, options) {
return 'foo: ' + Ember.get(options.data.view.content, property);
});
Handlebars template 把手模板
<script type="text/x-handlebars" data-template-name='app-view'>
<ul>
{{#each entry in content}}
<li>{{testHelper name}}</li>
{{/each}}
</ul>
</script>
Or even better, with this one: 甚至更好,有了这个:
Javascript 使用Javascript
Handlebars.registerHelper('testHelper', function(property) {
return 'foo: ' + Ember.get(this, property);
});
Handlebars template 把手模板
<script type="text/x-handlebars" data-template-name='app-view'>
<ul>
{{#each entry in content}}
{{#with entry}}
<li>{{testHelper name}}</li>
{{/with}}
{{/each}}
</ul>
</script>
My helpers are written in individual files, so I modified @MikeAski's answer to be the following. 我的助手是用单独的文件编写的,所以我修改了@ MikeAski的答案如下。
In helpers/my-helper.js
: 在
helpers/my-helper.js
:
var MyHelper = function(value) {
return moment(value).format("MMMM Do, YYYY");
};
export
default MyHelper;
At the top of app.js
: 在
app.js
的顶部:
// import modules
import myHelper from 'appkit/helpers/my-helper';
// register custom helpers
Ember.Handlebars.registerBoundHelper('myHelper', myHelper);
Then you don't even need the {{#with}}
in handlebars, just use as a normal helper. 然后你甚至不需要把
{{#with}}
的{{#with}}
,只需用作普通助手即可。
{{#each thing}}
{{myHelper thing.foo}}
{{/each}}
If you don't want to use a global helper then you could use a "pathed query": 如果您不想使用全局帮助程序,则可以使用“pathed query”:
{{#each entry in App.testController}}
<div>{{{../testHelper entry.name}}}</div>
{{/each}}
../
is the syntax for a pathed query. ../
是pathed查询的语法。 It causes you to traverse up the scope tree 1 level, and access private data from a parent scope. 它会导致您遍历范围树1级,并从父范围访问私有数据。 To traverse 2 levels upwards you could do the following
../../
. 要向上移动2个级别,您可以执行以下操作
../../
。 This is useful if you have nested for-loops. 如果你有嵌套的for循环,这很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.