How does the yield magic work in ActionView?

后端 未结 3 1581
名媛妹妹
名媛妹妹 2021-01-14 14:55

I was looking at how content_for works and observed the block.call in the capture_erb_with_buffer method. It apparently magically writes to the buf

3条回答
  •  有刺的猬
    2021-01-14 15:15

    This little tiny method called execute in ActionView::Base explains it all. http://google.com/codesearch/p?hl=en#m8Vht-lU3vE/vendor/rails/actionpack/lib/action_view/base.rb&q=capture_helper.rb&d=5&l=337

      def execute(template)
        send(template.method, template.locals) do |*names|
          instance_variable_get "@content_for_#{names.first || 'layout'}"
        end
      end
    

    The do |*names|... end block is the one receiving the yield. You'll notice that the @content_for_#{names.first} matches up with the variable being set in the content_for process.

    It's called from AV::TemplateHandlers::Compilable in #render, and I would assume other places as well.

      def render(template)
        @view.send :execute, template
      end
    

    http://google.com/codesearch/p?hl=en#m8Vht-lU3vE/vendor/rails/actionpack/lib/action_view/template_handlers/compilable.rb&q=execute&exact_package=git://github.com/payalgupta/todo-list.git&sa=N&cd=17&ct=rc&l=28

提交回复
热议问题