John
John

Reputation: 3296

Using linkTo within a custom Handlebars helper

I'm using a Handlebars helper to parse a set of objects and I'd like the returned result to be wrapped in a #linkTo call so Embers router will pick it up.

Here's how I'm calling it in the view: {{buildBreadcrumb my_objects}}

Here's what my helper looks like:

Ember.Handlebars.registerHelper 'buildBreadcrumb', (val, opts) ->
  value = Ember.get(this, val)
  out = ""
  value.forEach (group, index) =>
    if value.length - index == 2
      out += '{{#linkTo group ' + group.name + '}}'
    if value.length - index == 1
      out += '{{#linkTo group ' + group.name + '}}'
  out

The above just parses out the {{#linkTo ...}} as a literal string for obvious reasons. Is there any way that I can get it parsed the way I'm looking to do it? I'm well aware of the fact that I can use {{#each}}, etc... in the view itself - but because of my use-case I sort of have to use a helper to build this out. Any suggestions?

Upvotes: 2

Views: 650

Answers (1)

Darshan Sawardekar
Darshan Sawardekar

Reputation: 5075

You can write a custom Handlebars view helper. That view could encapsulate the #each logic while the final helper would look mostly similar to what you have here. The only difference in use is having to pass in the arguments as attributes to the View helper.

The way to create this helper is to pass in the View class instead of the helper function.

App.BreadcrumbView = Ember.View.extend({
  templateName: 'breadcrumb',
  penultimate: function() {
    var length = this.get('items').length;
    return this.get('items')[length - 2];
  }.property('items'),
  last: function() {
    var length = this.get('items').length;
    return this.get('items')[length - 1];
  }.property('items')
});

Ember.Handlebars.helper('breadcrumb', App.BreadcrumbView);

And the corresponding template,

<script type='text/x-handlebars' data-template-name='breadcrumb'>
  <ul class="breadcrumb">
    {{#each item in view.items}}
      <li>{{#linkTo 'group' item}}{{item.id}}{{/linkTo}} &raquo;
      </li>
    {{/each}}
  </ul>    
</script> 

And to use the helper in the app,

<script type='text/x-handlebars' data-template-name='breadcrumb'>
  <ul class="breadcrumb">
    <li>{{#linkTo 'group' view.penultimate}}{{view.penultimate.id}}{{/linkTo}} &raquo;</li>
    <li>{{#linkTo 'group' view.last}}{{view.last.id}}{{/linkTo}}</li>
  </ul>    
</script>  

A benefit with this approach is the bindings are automatically connected, so changing the items data would auto-update the breadcrumb view, preserving the internal Metamorphing.

Here's a jsbin example.

Upvotes: 2

Related Questions