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.
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?
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.
<a href="/about" class="<%= "active" if current_page?(path) %>">About</a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.