Nick
Nick

Reputation: 3160

Ruby if else statement one line not working

I have the following properly working line in a view that adds a class depending on the current_page of the user:

<li class="hvr-bottom <%= 'active' if current_page?(root_path) %>"> <%= link_to "Home", root_path %> </li>

Now I would also like to add a different class for the else situation, and I would prefer to do so while keeping it a single line (or is this not possible?) I was thinking of:

<li class="hvr-bottom <%= if(current_page?(root_path)) ? 'active' : 'inactive' %>"> <%= link_to "Home", root_path %> </li>

This produces the error:

syntax error, unexpected ')', expecting keyword_then or ';' or '\n' ...ath)) ? 'active' : 'inactive' );@output_buffer.safe_append='... ... ^ 

Any idea how I could make this work? Or is perhaps a single line not possible here?


I also tried the line below (which leaves out certain parenthesis) but it has the same result:

<li class="hvr-bottom <%= if current_page?(root_path) ? 'active' : 'inactive' %>"> <%= link_to "Home", root_path %> </li>

Upvotes: 1

Views: 232

Answers (1)

msergeant
msergeant

Reputation: 4801

You do not need to use "if" in the ternary. Change your statement to look like this:

<%= current_page?(root_path) ? 'active' : 'inactive' %>

Upvotes: 3

Related Questions