我有一个具有两个或三个主要“部分”的Ruby/Rails应用程序。当用户访问该部分时,我希望显示一些子导航。这三个部分都使用相同的布局,因此我无法“硬编码”导航到布局中。
我可以想到几种不同的方法来执行此操作。我想为了帮助人们投票,我将其作为答案。
还有其他想法吗?还是您投票赞成什么?
最佳答案
您可以使用局部函数轻松地做到这一点,假设每个部分都有其自己的 Controller 。
假设您有三个部分,分别称为帖子,用户和管理员,每个部分都有自己的 Controller :PostsController
,UsersController
和AdminController
。
在每个对应的views
目录中,声明一个_subnav.html.erb
部分:
/app/views/users/_subnav.html.erb /app/views/posts/_subnav.html.erb /app/views/admin/_subnav.html.erb
In each of these subnav partials you declare the options specific to that section, so /users/_subnav.html.erb
might contain:
<ul id="subnav">
<li><%= link_to 'All Users', users_path %></li>
<li><%= link_to 'New User', new_user_path %></li>
</ul>
虽然
/posts/_subnav.html.erb
可能包含:<ul id="subnav">
<li><%= link_to 'All Posts', posts_path %></li>
<li><%= link_to 'New Post', new_post_path %></li>
</ul>
最后,完成此操作后,只需要在布局中包括subnav部分:
<div id="header">...</div>
<%= render :partial => "subnav" %>
<div id="content"><%= yield %></div>
<div id="footer">...</div>