mar*_*ion 3 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1
所以在我application.html.erb看来,我的导航结构看起来像这样:
<div id="navigation">
<ul class="pills">
<% if current_page?(:controller => 'welcome', :action => 'index') %>
<li><%= link_to "Profile", vanity_path(:vname => current_user.username) %></li>
<li><%= link_to "Settings", settings_path %></li>
<li><%= link_to "Sign Out", signout_path %></li>
<% elsif !current_page?(:controller => 'welcome', :action => 'index') %>
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Profile", vanity_path(:vname => current_user.username) %></li>
<li><%= link_to "Settings", settings_path %></li>
<li><%= link_to "Sign Out", signout_path %></li>
<% end %>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
但是,我想要做的是,一旦它们出现在导航中的任何页面上,它就会将类应用于active相应的链接.
因此,例如,如果用户在mydomain.com/johnbrown哪个Profile链接上,则rails helper看起来像这样:
link_to "Profile", vanity_path(:vname => current_user.username), :class => "active".
但是我如何以编程方式做到这一点,所以我不是在复制内容?即如何为导航中的所有页面获取该功能并尽可能将其写为DRY?
谢谢.
这是一个非常好的问题.我从来没有真正对我见过或想出的解决方案感到满意.也许我们可以在这里一起来.
这是我过去尝试过的
我做了一个帮助器,它返回一个哈希:class,因为我使用HAML定义了
def active_tab(path)
request.path.match(/^#{path}/) ? { :class => 'active' } : {}
end
Run Code Online (Sandbox Code Playgroud)
ex用法:
= link_to "Dashboard", dashboard_path, active_tab("#{dashboard_path}$")
Run Code Online (Sandbox Code Playgroud)
或者沿着相同的路线替代
def active_class(path)
request.path =~ /#{path}/ ? 'active' : nil
end
Run Code Online (Sandbox Code Playgroud)
ex用法:
= link_to 'Presentations', admin_presentations_path, :class => "#{active_class('presentations')}"
Run Code Online (Sandbox Code Playgroud)
我很想看到其他一些建议.
| 归档时间: |
|
| 查看次数: |
3349 次 |
| 最近记录: |