Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class inline if ... (in 1 line)

I want to add a class to a link_to only if a statement is true.

<%= link_to product.name, product, :class => "last" if product == @products.last %>

The problem that the IF statement affects the whole line and not just the :class part.

I know i can get it done with IF ELSE, but is it possible to do it in 1 line ?

like image 589
Danpe Avatar asked Oct 02 '12 21:10

Danpe


2 Answers

<%= link_to product.name, product, :class => (product == @products.last ? "last" : "")  %>
like image 117
Alcides Queiroz Avatar answered Nov 05 '22 15:11

Alcides Queiroz


Well you could abstract this away in a helper:

def product_link(product)
  if product == @products.last
    link_to product.name, product, :class => "last"
  else
    link_to product.name, product
  end
end

Then in your view you can just do product_link(product).

Update: or in a more compact way:

def product_link(product)
  return link_to product.name, product, class: "last" if product == @products.last
  return link_to product.name, product)
end
like image 30
Agis Avatar answered Nov 05 '22 15:11

Agis