我有一个辅助导航栏,允许用户在其帐户的各个方面之间移动。
仪表板 |事件 |投资组合 |元素
我想让 current_page 的 CSS 加粗,这样当用户在“仪表板”上时,导航栏看起来像这样:
仪表板 |事件 |投资组合 |元素
我一直在摆弄
if current_page?(controller: 'users', action: 'edit)
<span class="bold">DASHBOARD</span>
else
DASHBOARD
end
和类似的代码,但它不起作用。原因是我用来生成 View 的嵌套部分。
例如,一个用户只能调出自己的账户信息,但由于每个用户可以有很多元素,所以我在views/projects/_list_by_owner.html.erb
下渲染了一个局部调用。 , 并传入
@projects = Project.where(:owner_id => current_user.id)
来自 users_controller#show
.
因为 View 是从 users_controller
生成的而不是 projects_controller
, 它没有选择正确的 current_page()
.
关于如何更深入地研究 Controller / Action 嵌套,或者动态生成 css 类的更好方法,有什么想法吗?
最佳答案
这是我会做的
辅助类
def currentp(path)
"bold" if request.url.include?(path)
end
查看
<%= link_to "users", posts_path, class: currentp(posts_path) %>
编辑:添加解释
如果您在 View (模板)中工作并且需要构建一些复杂的 HTML,例如一个甚至定义一个类,请使用帮助器。它还允许您在不连接到数据库的情况下更改数据的表示。
所以在 App >> helpers >> users_helper.rb 下
添加以下代码:
module LocationsHelper
def currentp(path)
"bold" if request.url.include?(path)
end
end
这将找到调用 currentp
的位置,如果页面在当前路径上,它将在 html 中定义类为 bold
。
然后你可以使用简单的css来定义粗体类
a.bold{
font-weight:700;
text-decoration:underline;
}
关于css - Rails 中的动态菜单类分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26185328/