如何根据Rails的值更改HTML输出 [英] How to change HTML output based on values in Rails
问题描述
我想简单地增加一个HTML类,如果返回的数据库值是一个具体的数字。这里是我的尝试:
I am trying to simply add an HTML class if a database value returned is a specific number. Here is what I tried:
<ul class="dog-sizes-list">
<li <%= if given_size == 1 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="30px" /></li>
<li <%= if given_size == 2 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="40px" /></li>
<li <%= if given_size == 3 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="50px" /></li>
<li <%= if given_size == 4 then puts "class='active'" end %>><img src="/assets/dogs/dog-icon.png" width="60px" /></li>
</ul>
但没有任何反应,也没有错误产生。此外,我跑了AR code。在控制台和它返回正确的值。具体做法是:
However nothing happens and no error is produced. Furthermore, I ran the AR code in console and it returned the correct value. Specifically:
given_size = Client.where(user_id: listing.client_id).first.dogsize
什么是最好的办法了吗?
What is the best approach for this?
推荐答案
您可以得到需要的结果以这种方式:
You could get the required result in this manner:
<li class="<%= "active" if given_size == 1 %>"></li>
如果您使用的是这种方法经常会被adivsable提取到一个辅助方法。助手可以放置到application_helper.rb文件或其他合适的地方
If you are using this kind of method regularly it would be adivsable to extract it into a helper method. The helper can be placed into your application_helper.rb file or other suitable place
def class_for_thing(thing)
if thing == whatever
"blah"
else
"not-blah"
end
这篇关于如何根据Rails的值更改HTML输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!