Ethem GÜR
Ethem GÜR

Reputation: 43

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?

Upvotes: 1

Views: 403

Answers (2)

Tony Babarino
Tony Babarino

Reputation: 3405

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 != '0' ? '' : 'disabled'} button big previous" %>
</li>

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

<% if @previous_page != '0' %>
    <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 %>

Upvotes: 1

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Use conditional as Tony suggested, but Tony's approach is a bit flawed because 0 is not false in Ruby. Try this

= link_to 'Previous Page', titles_path(page: @previous_page), class: "#{(@previous_page == '0')  ? 'disabled' : ''} button big previous"

Hope that helps!

Upvotes: 2

Related Questions