Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails defining Current_page

I am trying to use a basic current_page method to define whether a navigation link should be highlighted as the current page or not.

I am not receiving any errors at the moment but am clearly not defining things properly as it's not using my CSS correctly.

In my PagesController I have the following:

def current_page
  current_page = (path)
end

and I am using an if and else statement on my pages view to try and define which CSS line to use which looks like this:

<div id="nav">
  <ul>
    <li>
      <% if "current_page" %>
        <a href="/about" class="about-cp">About</a>
      <% else %>
        <a href="/about" class="about">About</a>
      <% end %>
    </li>
  </ul> 
</div>

I have read quite a few forums on this but still can't seem to get it right.

like image 564
Tom Pinchen Avatar asked Nov 30 '25 16:11

Tom Pinchen


2 Answers

Mhh you got an error in your code. With if "current_page" you will get always true, and only the first link will get rendered. You should use if current_page instead.

But rails has a build in helper, called current_page? for exactly this purpose:

Just do it like this:

 <% if current_page?(path) %>
   <a href="/about" class="about-cp">About</a>
 <% else %>
   <a href="/about" class="about">About</a>
 <% end %>

See here for more information on current_page?

like image 73
klump Avatar answered Dec 02 '25 05:12

klump


The klump's answer follows your requirement, but I dare to propose a different approach:

 <div id="nav">
  <ul>
   <li>
     <%= link_to_unless_current 'About', about_path %>
   </li>
  </ul> 
 </div>

This way your About will appear as a text if current page is about_path and as a link on any other.

like image 29
jdoe Avatar answered Dec 02 '25 05:12

jdoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!