我可以查看5个星号,产品的评级为5,等级为4等等的4个星号。但我想要做的是用我所拥有的星形图像替换星号我的资产/图像/目录,如果评级是4.5,那么显示半个星。有办法做到这一点吗?下面是我在application_helper.rb中的当前代码和index.html.erb中的视图。
application_helper.rb:
module ApplicationHelper
def render_stars(value)
output = ''
if (1..5).include?(value.to_i)
value.to_i.times { output += '*'}
end
output
end
end
index.html.erb:
<div id="star-rating">
<% if not product.no_of_stars.blank? %>
<div id="star-rating">
<% if product.no_of_stars.blank? %>
<%= link_to 'Please add a Review',{ controller: 'reviews', action: 'new', id: product.id } %>
<% else %>
Star rating: <%= render_stars(product.no_of_stars) %>
<% end %>
</div>
答案 0 :(得分:2)
假设您想使用star.gif
作为星形图像而half-star.gif
作为1/2星形图像:
module ApplicationHelper
def render_stars(value)
output = ''
if (1..5).include?(value.floor)
value.floor.times { output += image_tag('star.gif')}
end
if value == (value.floor + 0.5) && value.to_i != 5
output += image_tag('half-star.gif')
end
output.html_safe
end
end
答案 1 :(得分:0)
你可以尝试这样的事情:
module ApplicationHelper
def render_stars(value)
i_value = value.floor
f_value = value - i_value
output = '*' * i_value
output << image_tag('half_star.jpg') if f_value > 0
output
end
end
您可能必须在视图中使用.html_safe
。
但是,html.erb
代码段看起来不对。它将无法正确呈现,如果您未关闭文件中的某个if
,则会引发错误。你想要达到什么目标?