content_for vs yield in partials

后端 未结 1 1293
我寻月下人不归
我寻月下人不归 2020-12-31 16:44

In rails 3.0 with HAML (3.1.4) I have

  1. some template-like partial, like _template.html.haml:

    .panel.top
      = yield :panel_top
    
    .conte         
    
    
            
1条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 17:47

    From Rails 3.0 to Rails 3.2 content_for was really changed:

    3.0:

    def content_for(name, content = nil, &block)
        content = capture(&block) if block_given?
        @_content_for[name] << content if content
        @_content_for[name] unless content
    end
    

    3.2:

    def content_for(name, content = nil, &block)
      if content || block_given?
        content = capture(&block) if block_given?
        @view_flow.append(name, content) if content
        nil
      else
        @view_flow.get(name)
      end
    end
    

    This shows us, that from 3.2 content_for works for showing/inserting content too, not only store it for named section.

    Also, if you make an attempt to debug yield logic you'll se that it yields before content_for is correctly initialized.

    So, leaving fragment caching out of this discussion I can conclude that content_for is preferrable way to insert named sections anywhere except top-level layouts. In helpers and other situations yield should render wrong results.

    0 讨论(0)
提交回复
热议问题