正确的方法来在Rails助手中渲染fa_icons
我有一个Rails 4.2应用程序,它有一个评级系统。我想将演示者逻辑转移到助手中。我想根据排名是否完整来显示星星或半星。正确的方法来在Rails助手中渲染fa_icons
module ThingHelper
def calculate_stars(thing)
output = ""
total = thing.overall_average
thing.overall_average.ceil.times do |n|
if total >= 1
output += content_tag(:i, "<%= fa_icon 'star' %>")
total -= 1
else
output += content_tag(:i, "<%= fa_icon 'star-half' %>")
end
end
return output
end
end
在我的ERB模板,我有这样的:
<%= calculate_stars(thing).html_safe %>
然而,它只是列出了这样的字符串: “<%= fa_icon '明星' %>”。我尝试使用raw
以及使用concat
而不是+=
,但两种尝试的解决方案都只是渲染一个字符串。
我也试过没有content_tag
帮手,但那是行不通的。
我已经咨询了以下内容: http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag,How to embed font-awesome icons into submit_tag,和Ruby on Rails display half a star for a decimal rating, e.g. 4.5。
我错过了什么?由于
编辑
我不相信这可以在助手来完成,所以我只是不得不把逻辑视图。基本上,我围绕并计算完整星星的数量,然后根据四舍五入条件添加另一个星星。
你有两个错误是超小的。
首先,在您给内容标签的参数中。 Take a look at the documentation。在第一个例子...
content_tag(:p, "Hello world!")
# => <p>Hello world!</p>
的字符串就是那张标签之间。然而,需要将Font Awesome icons设置为类的的标签,其中没有内容之间的<i></i>
。
这意味着你需要传递content_tag
一个空字符串和哈希...
<%= content_tag(:i, "", class: "fa-icon star") %>
=> "<i class="fa_icon star"></i>"
我知道你在做其他的事情乘星和诸如此类的东西。我想你可以从这里拿...
你不需要声明一个字符串输出。
module ThingHelper
def calculate_stars(thing)
total = thing.overall_average
thing.overall_average.ceil.times do |n|
if total >= 1
content_tag(:i, :class => "fa fa-list") do
end
total -= 1
else
content_tag(:i, :class => "fa fa-list") do
end
end
end
end
end
然后呈现在您的ERB:
<%= calculate_stars(thing) %>
请注意,我用的引导和glyphicons我的图标。只需更改图标类。
我已在开发了尝试,生成此:
我不知道我不需要明确的回报。谢谢你的帮助。 – user3162553
你已经解决了这个问题@ user3162553? –
是的,我有。我已经标记了一个选择的答案。 – user3162553
感谢。这工作。您指出的问题是我传递给'content_tag'的参数。 – user3162553