Rails如何从外部引用块内已有的内容

时间:2013-11-25 04:16:37

标签: ruby-on-rails ruby ruby-on-rails-4

有没有办法在迭代实际开始之前从块外部的块获取结果变量?

我希望能够获得active变量并输出"collapse"所在的位置。

到目前为止,我的代码如下。

def sidebar_menu_item(top_menu_args, data_target, sub_menu_args, icon = "angle-left")
        haml_tag :li, :class => "panel" do
            haml_tag:a, :href => "#", :class => "accordion-toggle", "data-present" => "#menu", "data-toggle" => "collapse", "data-target" => "##{data_target}" do
                haml_concat "<i class='fa fa-#{top_menu_args[1]}'></i> #{top_menu_args[0]}"
                haml_tag :span, :class => "pull-right" do
                    haml_tag :i, :class => "fa fa-angle-left"
                end
            end
            haml_tag :ul, :class => "collapse", :id => data_target do
                sub_menu_args.each do |menu_args|
                    link = menu_args[0]
                    label = menu_args[1]
                    action = "/#{params[:action]}" if params[:action] != "index"
                    current_uri = "/#{params[:controller]}#{action}"
                    if link == current_uri
                        active = { :class => "active" }
                    end
                    haml_tag :li, active do
                        haml_tag :a, :href => link do
                            haml_concat "<i class='fa fa-angle-right'></i> #{label}"
                        end 
                    end
                end
            end
        end
    end

2 个答案:

答案 0 :(得分:0)

我不认识哈姆,但你可以这样做吗?

您可以将目标传递给current_page方法,如下所示:

current_page?(root_path) 

它将返回true或false。然后有类似的东西:

:class => ("active" if current_page?(root_path))

答案 1 :(得分:0)

你可以用map迭代而不是每次都会返回元素数组

sub_menu_args.map do |menu_args|
                link = menu_args[0]
                label = menu_args[1]
                action = "/#{params[:action]}" if params[:action] != "index"
                current_uri = "/#{params[:controller]}#{action}"
                active = { :class => "active" } if (link ==current_uri)                 
            end