Reputation: 233
Rails 3.1 Trying to style the display value on a div to none if a variable is nil
I have tried the following in my view:
<tr class = "level3" <%= attributes["style"] = "display: none" if product.volume3.nil? %>>
<td><%=product.volume3%></td>
<td><%= number_to_currency (product.price3)%></td>
any help is appreciated
Upvotes: 0
Views: 2520
Reputation: 35349
Personally I would write a helper and use content_tag_for
with a CSS class.
= content_tag_for :tr, product, class: "#{'hidden' if product.volume3.nil?}" do
# rest of code
CSS:
.hidden { display: none; }
If you want to get fancy, add a helper:
def class_for(product)
'hidden' unless product.volume3.present?
end
= content_tag_for :tr, product, class: class_for(product) do
Rails already has tools to solve these problems, and I would not recommend littering your views with conditions.
Finally, as others have commented, you should only render the <tr>
if you need to.
= if product.volume3.nil?
<tr> etc...
Upvotes: 0
Reputation: 7657
If there's no reason for it to be displayed if volume3 is nil, you may just want to do it like this instead:
<% unless product.volume.nil? %>
<tr class="level3">
# etc etc.
<% end %>
Upvotes: 0
Reputation: 44880
Render things you know as HTML as HTML and not as strings. The way you wrote it returns an HTML-unsafe string. Since you know you are rendering HTML, put it between conditionals and render it as raw HTML:
<tr class="level3" <% if product.volume3.nil? %>style="display:none;"<% end %>>
<td><%=product.volume3%></td>
<td><%= number_to_currency (product.price3)%></td>
</tr>
Upvotes: 3
Reputation: 38645
Adding to what has already been shown in comment by MrYoshiji, you don't need to generate the style
attribute if it's going to have no value. Try:
<tr class = "level3"<%= " style='display: none';" if product.volume3.nil? %>>
Upvotes: 1