evianpring evianpring - 1 year ago 108
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

Answer Source

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!"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download