Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set HTML element id with HAML

Tags:

I am attempting to write this html in haml so as to add an id tag if the item is the current one. This is to setup for jquery highlighting.

<% if line_item == @current_item %>
<tr class="line_item id="current_item">
<% else %>
<tr class="line_item">
<% end %> 
  <td><%= line_item.quantity %>&times;</td>
  <td><%= line_item.product.title %></td> 
  <td class="item_price"><%= number_to_currency(line_item.total_price) %></td>
</tr>

Because I don't want to write a helper method, I've stuck the if statement within the tag:

%tr.line_item{ :id => (line_item == @current_item ? '' : 'current_item') }
%td
    = line_item.quantity
%td 
    \x #{line_item.product.title}
%td.item_price
    = number_to_currency(line_item.total_price)
%td.item_remove
    = button_to 'Remove', line_item, :method => :delete

However, this id tag of 'current_item' sticks with all the items and not just the current one. This results in javascript highlighting all or the wrong entry. Thoughts on how to get haml to cooperate?

like image 843
ScotterC Avatar asked Oct 01 '10 16:10

ScotterC


People also ask

How do I give a HAML ID?

In Haml, we write a tag by using the percent sign and then the name of the tag. This works for %strong , %div , %body , %html ; any tag you want. Then, after the name of the tag is = , which tells Haml to evaluate Ruby code to the right and then print out the return value as the contents of the tag.

What is Haml in CSS?

Haml is a markup language that's used to cleanly and simply describe the HTML of any web document, without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ERB, and ASP.


2 Answers

Ehm sir, your condition is wrong :-)

It should be

line_item == @current_item ? "current_item" : ""

There is a thing that's not pretty - you end up with id="" for rest of the items. But there is a simple cure for it:

%tr.lineitem{ :id => (line_item == @current_item ? "current_item" : nil)}

When you return nil value for an attribute HAML will ignore it and it will not appear in the output.

like image 98
Radek Paviensky Avatar answered Sep 23 '22 17:09

Radek Paviensky


This also works as an alternative for the first solution in the accepted answer

= f.input_field :hello, disabled: (true unless SOME_CONDITION_HERE)
like image 44
vladCovaliov Avatar answered Sep 19 '22 17:09

vladCovaliov