2

ユーザーが表示しているページに応じてレンダリングされる動的サブメニューがあります。次のコードを _sub_menu.html.erb パーシャルに配置しました。

<a href="/dashboard/index" class="current">Index</a>
<a href="/dashboard/account">Account</a>
<a href="/dashboard/payments">Payments</a>`

私の主な見解から、私は を呼び出します<%= render 'sub_menu' %>。これは機能します。

ただし、ユーザーがどのページにいるかに応じて、class="current" の部分を変更したいと考えています。ローカルパラメーターを渡してレンダリングすることでレンダリングからこれを行うことを望んでいましたが、それはハックのようです:

<%= render 'sub_menu' , :locals => {:active_item => 'payments'} %>

さらに、ロジックは本当に醜くなります。これを行うより良い方法はありますか?

4

2 に答える 2

2

link_to_unless_currentを呼び出す追加のヘルパー メソッドを定義できます。

def link_to_current_with_class(name, current_class, options = {}, html_options = {}, &block)
  link_to_unless_current(name, options, html_options) do
    options[:class] = current_class + " " + options[:class]
    link_to(name, options, html_options)
  end
end

次に、ナビゲーション部分から呼び出します。

<%= link_to_current_with_class "Index", "current", "/dashboard/index" %>
于 2010-10-21T14:41:32.207 に答える
2

link_to_unless_currentリンクが現在のページである場合にレンダリングするコンテンツを提供するブロック パラメーター to を利用できると思います。

<%= link_to_unless_current("Index", :action => 'index') { link_to("Index", {:action => 'index'}, {:class => 'current' }) %>
<%= link_to_unless_current("Account", :action => 'account') { link_to("Account", {:action => 'account'}, {:class => 'current' }) %>
<%= link_to_unless_current("Payments", :action => 'payments') { link_to("Payments", {:action => 'payments'}, {:class => 'current' }) %>

それは動作しますか?

于 2010-10-21T14:31:01.077 に答える