ember-cli support for Handlebars @vars in each helper (i.e., @index, @key, @first, @last)

孤者浪人 提交于 2019-11-30 04:56:51

问题


I am getting a compilation error in ember-cli whenever I have a Handelbars template that uses @vars variables (i.e., @index, @key, @first, @last) inside of the each helper. (See http://handlebarsjs.com/#iteration for documentation on these @vars variables inside the each helper.) Below is a simple application built using ember-cli and containing only two files added to the program: routes/application.js and templates/application.hbs. At the bottom of this post is a screenshot of the compilation error message given by ember-cli. Is there an error in my code? Or is this a bug I should report on github @ https://github.com/stefanpenner/ember-cli?

routes/application.js

export default Ember.Route.extend({
    model: function() {
        return ['red', 'blue', 'green'];
    }
});

templates/application.hbs

{{#each model}}
  {{@index}}: {{this}}
{{/each}}

Screenshot of ember-cli compilation error message:

Here are the versions of the various tools involved:

  • ember-cli: 0.0.40
  • node: 0.10.30
  • npm: 1.4.21
  • Handlebars: 1.3.0
  • Ember: 1.6.1

回答1:


That really isn't related to ember-cli. Ember Handlebars doesn't support the @keyword items.




回答2:


It's possible to mimic behavior of following Handlebars keywords: @index, @key, @first, @last.

@index

{{#each array as |item index|}}
  Index of item: `{{item}}` is: `{{index}}`
{{/each}}

@key

{{#each-in object as |key value|}}
  {{key}}: {{value}}
{{/each-in}}

@first

You could also mimic behavior of @first using ember-truth-helpers addon and taking advantage of eq helper - thanks to kristjan reinhold for this idea:

{{#each array as |item index|}}
  {{#if (eq index 0)}}
    <!-- first element specific html -->
  {{else}}
    <!-- other html -->
  {{/if}}
{{/each}}

Instead of (eq index 0) you can use (eq item array.firstObject).

@last

As dwickern suggested you can use Ember.Array.lastObject to mimic @last behavior.

{{#each array as |item|}}
  {{#if (eq item array.lastObject)}}
    <!-- last element specific html -->
  {{else}}
    <!-- other html -->
  {{/if}}
{{/each}}


来源:https://stackoverflow.com/questions/25395355/ember-cli-support-for-handlebars-vars-in-each-helper-i-e-index-key-firs

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