如何解决在Rails中给定字符串模式来更改元素样式
根据路由,更改内容将active
类赋予li
。
我有这条路线:
/profile/2
/profile/2/info
/profile/2/contact
我有一个菜单
<ul>
<li>
<%= link_to 'Profile',profile_path(current_user),class: current_class_contains?('/profiles') %>
</li>
<li>
<%= link_to 'Info',info_profile_path(current_user),class: current_class_contains?('/info') %>
</li>
<li>
<%= link_to 'Contact',contact_profile_path(current_user),class: current_class_contains?('/contact') %>
</li>
</ul>
在application_helper
module ApplicationHelper
def current_class_contains?(test_path)
return "active" if request.path.match(test_path)
""
end
def current_class?(test_path)
return "active" if request.path == test_path
""
end
end
我遇到的问题是,如果我在/profile/2/info
或/profile/2/contact
中,则配置文件li
也将获得active
类。
我不知道。有什么想法吗?
解决方法
使用current_page?,类似以下内容
return "active" if current_page? test_path
&呼叫
current_class_contains?(profile_path(current_user))
,
我会使用current_page?
构建这样的帮助方法:
def indicating_link_to(name,url)
css_class = 'active' if current_page?(url)
link_to(name,url,class: css_class)
end
并在您的视图中使用这种帮助方法:
<ul>
<li>
<%= indicating_link_to 'Profile',profile_path(current_user) %>
</li>
<li>
<%= indicating_link_to 'Info',info_profile_path(current_user) %>
</li>
<li>
<%= indicating_link_to 'Contact',contact_profile_path(current_user) %>
</li>
</ul>
并且随着将在Ruby on Rails 6.1中引入的新class_names
方法,它将变得更加简单:
def indicating_link_to(name,url)
link_to(name,class: class_names(active: current_page?(url)))
end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。