是否可以使用 ERB 库评估 html.erb 模板中的 yield 语句?

Is it possible to evaluate a yield statement in an html.erb template using the ERB library?

我参考的ERB库是ERB.

require 'ERB'
simple_template = "Statement: <%= yield %>."
renderer = ERB.new(simple_template)

我希望能够传入要在 simple_template 中的 yield 语句中使用的块。有什么方法可以用 ERB 库做到这一点吗?

以下无效:

renderer.result { "I am yielded" }  # LocalJumpError: no block given (yield)

也没有:

prc = Proc.new { "I am yielded" }
renderer.result(prc) # TypeError: wrong argument type proc (expected binding)

有没有比使用 ERB 库更好的方法?

这个问题似乎是指在 application.html.erb 中的 Rails 应用程序中发生的事情。

更新: 这是我发现的重复问题: yield in ERB without rails

您需要将您想要的块传递到您创建将与模板一起使用的 Binding 的上下文:

require 'erb'


def render(name)
  TEMPLATE.result(binding)
end

render('evianpring') { 'blocks' }
# => "evianpring yields to the power of blocks!"

让我们深入了解为什么会这样。来自绑定文档:

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained.

那么在此处创建的绑定的执行上下文中有什么可用的?

def render(name)
  TEMPLATE.result(binding)
end
  • #render() 的任何局部变量,如 name
  • 任何像 TEMPLATE
  • 这样的全局变量
  • 我们传递给 #render()
  • 的任何块

因此如果我们想使用 yield 需要传递一个块给 #render()