简体   繁体   English

Rails 导航助手方法

[英]Rails navigation helper method

I have two rails helper on my application helper:我的应用程序助手上有两个 rails 助手:

  def active_class(link_path)
    current_page?(link_path) ? 'active' : ''
  end

  def active_class_white(link_path)
    current_page?(link_path) ? 'active-white' : ''
  end

One is for regular links the other one is for the submenus.一种用于常规链接,另一种用于子菜单。 Usually I place the link like this:通常我这样放置链接:

 <%= link_to "Home", root_path(:anchor => 'home'), class: "nav-link #{active_class('/')}", :"data-id" => "home" %>

Now here's my problem.现在这是我的问题。 On my homepage I got this link where it will slide to a particular section of the site thus requires a character like #about .在我的主页上,我得到了这个链接,它会在那里滑动到网站的特定部分,因此需要一个像#about这样的字符。 If I place:如果我放置:

<%= link_to "About", root_path(:anchor => 'about'), class: "nav-link #{active_class('/#about')}", :"data-id" => "about" %>

It's still putting the active class on the home text instead of the about (the homepage is a one page slider type).它仍然将活动类放在home文本上,而不是关于(主页是单页滑块类型)。

Another thing is that for complicated url like the devise edit profile, I tried to put the ff:另一件事是,对于像设计编辑配置文件这样的复杂网址,我尝试将 ff:

<%= link_to "Edit Profile", edit_user_registration_path(current_user), class: "dropdown-item #{active_class_white('/users/edit/:id')}" %> 

Placing /users/edit/:id doesn't work on this kind of URL: http://localhost:3000/users/edit.13放置/users/edit/:id对这种 URL 不起作用: http://localhost:3000/users/edit.13

On this two kinds of URL my code doesn't work.在这两种 URL 上,我的代码不起作用。 Any idea how to make them work or turn this around?知道如何让它们工作或扭转局面吗?

Anchors are purely client-side and are not sent along with the request to the server.锚点纯粹是客户端,不会与请求一起发送到服务器。 So, the only way to implement the first part of your question is through Javascript.因此,实现问题第一部分的唯一方法是通过 Javascript。 You can listen for a click event on links then add the active class to the one that was clicked.您可以监听链接上的点击事件,然后将活动类添加到被点击的类中。

The second part of your question, where you pass in the :id segment key, can be solved by passing a route helper (along with an object) to current_page?您问题的第二部分,您传入:id段键,可以通过将路由助手(连同对象)传递给current_page? instead of an explicit string...而不是显式字符串...

class: <%= active_class(edit_user_registration_path(current_user)) %>

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

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