问题
How can I call a handlebars block helper from another helper in ember.
I am interested in converting the following in a bound helper.
{{#each link in sideMenuLinks}}
<li class="navigation page">
{{#linkTo ROUTE_VARIABLE link.linkToRouteContext}}
{{{link.iconTag}}}<i class="icon-right-open"></i>{{link.linkText}}</a>
{{/linkTo}}
</li>
{{/each}}
Note that I will have to call a {{#linkTo}} block inside the helper and also change ROUTE_VARIABLE with a value from the property link.linkToRoute.
回答1:
The Ember handlebars helpers are placed at Ember.Handlebars.helpers. You can call them with Ember.Handlebars.helpers.{helperName}.call.
However, The above looks like a dynamic partial/view style helper. I would suggest creating a Handlebars View helper for it. The syntax is similar but you pass in a View class to the helper.
Ember.Handlebars.helper('sideMenuLinks', App.SideMenuLinksView);
The corresponding view can use a template similar to yours by giving a templateName
App.SideMenuLinksView = Ember.View.extend({
templateName: 'sideMenuLinksTemplate'
});
You template would be something like,
<script type='text/x-handlebars' data-template-name='sideMenuLinksTemplate'>
{{#each link in view.links}}
<li class="navigation page">
{{#linkFor parentView.routeVariable link.linkToRouteContext}}
{{{link.iconTag}}}<i class="icon-right-open"></i>{{link.linkText}}</a>
{{/linkFor}}
</li>
{{/each}}
</script>
The default Ember linkTo is static, In that you cannot pass the named route from a variable. You will need a dynamic linkTo helper like the linkFor that looks up the variable path before
applying linkTo internally.
Ember.Handlebars.registerHelper('linkFor', function(path, params, options) {
var view = options.data.view;
var name = view.get(path);
var args = [name, params, options];
return Ember.Handlebars.helpers.linkTo.apply(this, args);
});
Finally you can use this helper like below. The links property will be bound to the content of the controller in this example.
<script type='text/x-handlebars' data-template-name='application'>
{{sideMenuLinks links=content routeVariable='page'}}
</script>
Here's a working jsbin.
来源:https://stackoverflow.com/questions/17532878/calling-a-handlebars-block-helper-from-another-helper