content_for vs yield in partials

夙愿已清 提交于 2019-11-30 09:07:48

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!