Ethem GÜR Ethem GÜR - 9 months ago 26
CSS Question

Rails change html element attribute in link_to

I'm creating a Previous Page button. This is my button:

<li>
<%= link_to "Previous Page", titles_path(:page => @previous_page), class:"button big previous" %>
</li>


If page is 0, it should be disabled. My new button should be like this:

<li>
<%= link_to "Previous Page", titles_path(:page => @previous_page), class:"disabled button big previous" %>
</li>


I mean, I should use if-else in link_to, and according to the if-else my code should change class of my button.

How can I do that?

Answer Source

You can use conditional operator ? : to insert something directly into class string:

<li>
<%= link_to "Previous Page", titles_path(:page => @previous_page), class:"#{@previous_page ? '' : 'disabled'} button big previous" %>
</li>

or simply use <% if %> <% else %>:

<% if @previous_page %>
    <li>
    <%= link_to "Previous Page", titles_path(:page => @previous_page), class:"button big previous" %>
    </li>
<% else %>
    <li>
    <%= link_to "Previous Page", '', class:"disabled button big previous" %>
    </li>
<% end %>