0
0

More than 3 years have passed since last update.

【Rails6, haml】クラス名にindexをつける方法【each_with_indexまたはeach.with_index】

Posted at

やりたいこと

eachメソッドで並べるデータそれぞれのクラス名に番号を付けたい。
具体的には
user_name_1
user_name_2
user_name_3
のような感じ。

開発環境

ruby 2.6.5
rails 6.0.0

コード例

hogehoge.html.haml
- @products.each.with_index do |product, index|
  %tr.results__table-row
    %td.results__table-row__name
      = product.standard_name
    %td{class: "results__table-row__price_#{++index}"}
       = (product.price).to_s(:delimited)

この部分ですね。

%td{class: "results__table-row__price_#{++index}"}

普通、hamlだとクラス名は.hogehogeとしますが、
式の展開があるから? {class: "hogehoge"}となっています。

文字列の中での展開なので、#{~~}はいつも通りですね。

したがって、

%td{class: "hogehoge_#{++index}"}

となります。

ちなみに

each_with_indexの時はindexは0から始まり、
each.with_indexの時はindexは1から始まりますよ〜

0
0
0

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
0
0