evianpring evianpring - 7 months ago 45
Ruby Question

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

The ERB library I refer to is ERB.

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

I want to be able to pass in a block to be used in the
statement in
. Is there some way to do this with the ERB library?

The following does not work:

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

Neither does:

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

Is there a better way to do this than using ERB library?

This question seems to refer to what happens in a Rails application in application.html.erb.

Here are question duplicates I found:
yield in ERB without rails


You need to pass the block you want to yield to Binding you'll use with the template:

require 'erb'

TEMPLATE = ERB.new("<%= name %> yields to the power of <%= yield %>!")

def render(name)
  TEMPLATE.result(binding { yield })

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