简体   繁体   中英

How to define a custom helper in handlebars ember

How can i write a ember handlebars helper that will display this:

<div value="40">text</div>

I need to customize value and text here. And bind those values to the context.

My approach doesn't quite work:

I define a helper:

Ember.Handlebars.helper('progress-bar', function(value, options) {
    return '<div value="' + value + '">' + options.text + '</div>';
});

then use it:

{{progress-bar value="50" text="this.status"}}

How can i access the parameters passed to the helper in the template when defining a Handlebars helper?

Since you're using Ember, you can use an ember component instead of a plain handlebars helper.

Example:

 <script type="text/x-handlebars" id="index">
   {{my-component value="foo" text="bar"}}
 </script>

<script type="text/x-handlebars" id="components/my-component">
  <div {{bind-attr value="value"}}>
    {{text}}
  </div>
</script>

The nice thing about using a component is that you don't necessarily need to write any javascript - Ember generates all the plumbing code. You can find more info about components here: http://emberjs.com/guides/components/defining-a-component/

Do it as follows,

http://emberjs.jsbin.com/yimecihutuka/1/edit

hbs

<script type="text/x-handlebars" data-template-name="index">
    <ul>
    {{#each item in model}}
      <li>{{item}}</li>
    {{/each}}
    </ul>

    {{progress-bar "50" status}}
  </script>

js

App.IndexController = Ember.Controller.extend({

  status:"the status"
});


Ember.Handlebars.helper('progress-bar', function(value, status) {
    return new Ember.Handlebars.SafeString('<div value="' + value + '">' + status+ '</div>');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM