在 ActionView 中,yield 魔法是如何工作的? [英] How does the yield magic work in ActionView?

查看:48
本文介绍了在 ActionView 中,yield 魔法是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是查看 content_for 如何工作并观察 capture_erb_with_buffer<中的 block.call/代码>方法.它显然神奇地写入缓冲区变量,然后对其进行修剪.但是,我认为这已被弃用,您现在可以调用 <%=yield :tag%> .这是如何运作的?如果我从 ERB 模板调用 yield 到哪里?

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 buffer variable which is then pruned. However, this I believe is deprecated and you can just call <%=yield :tag%> now. How does this work? If I call yield from an ERB template where does that yield to?

如果能提供一个简单的代码示例来说明这一点,我们将不胜感激.

A simple code sample to illustrate the point would be greatly appreciated.

推荐答案

ActionView::Base 中名为 execute 的这个小方法说明了一切.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

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

do |*names|... end 块是接收yield 的块.您会注意到 @content_for_#{names.first}content_for 过程中设置的变量相匹配.

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.

它是从#render 中的 AV::TemplateHandlers::Compilable 调用的,我也会假设其他地方.

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

这篇关于在 ActionView 中,yield 魔法是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆