我的rails应用程序中有一个博客部分,并且想知道根据将要打开的页面处理分配CSS类active
的好方法是什么。
这是否应该通过if
和do
语句.erb
来完成?它需要反映该员额所属的类别。
博客类别表:
create_table "blog_categories", force: :cascade do |t|
t.string "name"
t.integer "parent_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
帖子表列:t.integer "category_id"
- 存储此内容以与猫的.id
相关。
我的类别用NULL
parent_id
表示,子类别是那些parent_id
设置为主类别.id
的类别。
您可以通过在 application_helper.rb 中定义一个函数来执行此操作
def active_class(path)
"active" if current_page?(path)
end
如果用户与 path 参数中传递的 URL 位于同一 URL 上,则current_page?
方法将返回活动状态。 查看其文档。
那么在视图中,您可以像这样使用它。
<li class="<%= active_class new_user_session_path %>">
我希望你在下面使用这些帮助程序 一个用于单路径 例如:
<li class="<%= active_class(first_path) %>">
def active_class(link_path)
current_page?(link_path) ? 'active' : ''
end
这个用于多个链接数组 例如
<li class="<%= active_class_multiple([first_path, second_path]) %>">
# pass array of paths to get current page active link
def active_class_multiple(array)
array.include?(request.path) ? 'active' : ''
end