在我的非高压页面上,如果用户在页面上,我将使用以下代码向导航元素添加“活动”类:<li class="<%= 'active' if params[:controller] == 'home' %>"><a href="/">Home</a></li>
对我的 high_voltage 页面执行此操作的等效方法是什么(我想要 li 上的活动类)?
<li class="nav-item"><%= link_to 'Plans', page_path("plans") %></li>
在我的非高压页面上,如果用户在页面上,我将使用以下代码向导航元素添加“活动”类:<li class="<%= 'active' if params[:controller] == 'home' %>"><a href="/">Home</a></li>
对我的 high_voltage 页面执行此操作的等效方法是什么(我想要 li 上的活动类)?
<li class="nav-item"><%= link_to 'Plans', page_path("plans") %></li>
我最终得到了这个:
<li class="nav-item <%= 'active' if page_path == '/about' %>">
<%= link_to "About", page_path("about") %>
</li>
高压提供了page_path
链接到页面的方法。我可以使用它来确定我是否在该页面上,就像我对控制器所做的那样。
您可以使用 high_voltage 的page_path
功能current_page?
<li class='<%="active" if current_page?page_path('about') %>'>About</li>
<li class='<%="active" if current_page?page_path('contact') %>'>Contact</li>
还有另一种解决方案可以将条件逻辑排除在您的视图之外,并使用纯 CSS 来标记您的活动导航项。它可以与您的所有视图一起使用,包括 high_voltage 页面。
module ApplicationHelper
def body_class
"#{controller_name} #{controller_name}-#{controller.action_name} #{params['id']}"
end
def controller_name
controller.controller_path.gsub('/','-')
end
end
从布局中调用辅助方法
<body class="<%= body_class %>">
这会给你一个像这样的身体PagesController#show
课程id=plans
<body class="pages pages-show plans">
导航的 html 看起来像这样
<ul class="nav-items">
<li class="home">Home</li>
<li class="plans">Plans</li>
<li class="contact">Contact</li>
</ul>
然后你可以使用 CSS 来定位你想要激活的导航项
body.home li.home,
body.plans li.plans,
body.contact li.contact {
// styles for active item
}
由于它是静态页面,您可以直接用 HTML 代码编写它:
<li class="active nav-item"><%= link_to 'Plans', page_path("plans") %></li>