LoginSignup
1
1

More than 5 years have passed since last update.

Ember.Handlebars.helpers.eachでindexを使って何かする方法

Posted at

以前はeachのループ内で@firstとか@lastを使えたようなのですが、現在(2015年2月10日時点)では使えなくなっています。

indexを取る方法といえばこれしかありません

templates/items.hbs
{{#each item in items}}
  index: {{_view.contentIndex}}
{{/each}}

この_viewとかprivate感バリバリであんまり使いたくないんですけど…。
arrayを回してlink-toして最後以外はコンマを出力したかったので大分悩みました。

たどり着いた方法はこれです

templates/items.hbs
{{#each item in items}}
  {{link-to item.name 'item' item}}{{unless-last ',' item items}}
{{/each}}
helpers/unless-last.js
Ember.Handlebars.helper('unless-last', function(str, item, array) {
  var result = item === array[array.length - 1] ? '' : str;
  return new Ember.Handlebars.SafeString(result);
})

出来てみれば案外あっさりでしたが、ハマると怖い。ifヘルパーには引数を1つしか渡せないし、ブロックを渡すヘルパーはviewを作らなくちゃいけないので今回の場合はコンマ表示したいだけで大げさな実装です。
この方法を応用すればいろいろ出来そうです。

あー解決してよかった。

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1