简体   繁体   English

Rails定义Current_page

[英]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. 我正在尝试使用一种基本的current_page方法来定义是否应将导航链接突出显示为当前页面。

I am not receiving any errors at the moment but am clearly not defining things properly as it's not using my CSS correctly. 我目前没有收到任何错误,但由于未正确使用CSS,因此显然定义不正确。

In my PagesController I have the following: 在我的PagesController中,我具有以下内容:

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: 并且我在页面视图上使用了if and else语句来尝试定义要使用的CSS行,如下所示:

<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. if "current_page"您将始终为true,并且仅显示第一个链接。 You should use if current_page instead. 您应该使用if current_page代替。

But rails has a build in helper, called current_page? 但是Rails有一个内置的帮助程序,称为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? 有关current_page?更多信息,请参见此处 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. 这样,如果当前页面是about_path ,则您的About将显示为文本,而其他页面上的链接则显示为文本。

<a href="/about" class="<%= "active" if current_page?(path) %>">About</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM