【问题标题】:How to use rails helper method that takes in an icon as an argument?如何使用将图标作为参数的rails辅助方法?
【发布时间】:2017-02-01 07:07:10
【问题描述】:

我想创建一个给我星级评分的方法。星星将来自 fontawesome 的starstar-half。我创建了下面的方法来进行评级(浮动。0.0 到 5.0,以 0.5 为增量)。半星将是<i class="fa fa-star-half" aria-hidden="true"></i>,星将是<i class="fa fa-star" aria-hidden="true"></i>。如果评级为 3.5,则预计返回 (3 × star) + (1 × half-star)。

def star_rating(rating, star, half_star)
  star = star
  half_star = half_star
  if ((rating % 1).round == 1) #ends with 0.5
    result = (rating - 0.5).round * star + half_star
  else
    result = rating * star
  end
  return result
end

我以前从未做过这样的事情。我最初的想法是将star_rating() 放入Ruby 助手(在本例中为posts_helper.rb)。

在帖子index.html.erb 看来,我做了<%= star_rating(post.rating, <i class="fa fa-star" aria-hidden="true"></i>, <i class="fa fa-star-half" aria-hidden="true"></i>) %>,但它抛出了一个错误。

简而言之,我有一个 ruby​​ 方法,它从模型 (post.rating) 和两个图标 (fa-starfa-star-half) 中获取一个值。将 ruby​​ 方法与 fontawesome 的图标结合使用以达到预期星级的最佳做法是什么?

我知道有几个宝石可以做到这一点,但我试图从头开始,以帮助我更多地了解 Rails。

【问题讨论】:

  • 您是否有理由需要将starhalf_star 作为参数传递?这些论点会与上述不同吗?
  • 是的,它们是原始设计的一部分。参数本身可以更改,但输入/输出需要是(评级)->(功能)->(根据评级显示星和半星)

标签: html ruby-on-rails


【解决方案1】:

我真的不确定显示评分槽助手是否正确。 但这应该可行:

创建部分文件

# _rating.html.erb
<%= fa_icon "#{icon_name}" %>

添加到您需要的视图文件

# view.html.erb
<%= show_raiting(3.3) %>

并将方法添加到帮助程序,其中path/to/your 是_rating.html.erb 模板的路径

#***_helper.rb
def show_raiting(rating)
    rating = rating.to_f
    if rating.present?
      output_stars = ''
      rating.floor.times do
        output_stars += render partial: 'path/to/your/rating', locals: { icon_name: 'star' }
      end
      output_stars += render partial: 'path/to/your/rating', locals: { icon_name: 'star-half' } unless rating % 1 == 0
      output_stars.html_safe
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 2012-02-07
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多