Yield and default case || do not output default case

前端 未结 7 1396
刺人心
刺人心 2021-02-14 15:49

I have a simple yield use case and for some unknown reason the default case is never shown:

In my super_admin layout I have:

<%= yield :body_id || \'s         


        
7条回答
  •  耶瑟儿~
    2021-02-14 16:24

    Why no test if there are a content_for or not define in view compilation.

    In the content_for code we can see :

    def content_for(name, content = nil, &block)
      ivar = "@content_for_#{name}"
      content = capture(&block) if block_given?
      instance_variable_set(ivar, "#{instance_variable_get(ivar)}#{content}".html_safe)
      nil
    end
    

    So in your case, the @content_for_body_id is define if a content_for is in your view.

    You can made :

    <%=  instance_variable_defined?('@content_for_body_id') ? yield(:body_id) : 'super_admin_main' %>
    

    If you prefere you can generate an helper after

    def yield_or(part, result)
      instance_variable_defined?("@content_for_#{part}") ? instance_variable_get("@content_for_#{part}") : result
    end
    

    and call it in your view by

    <%= yield_or(:body_id, 'super_admin_main') %>
    

    It's works only with Rails 2.3.x

    In Rails 3 :

    there are this method content_for?

提交回复
热议问题