[Ruby] ERB block question

James Hillyerd james at hillyerd.com
Mon Aug 13 21:09:20 PDT 2007


On 8/12/07, James Hillyerd <james at hillyerd.com> wrote:
>
> Hello,
>
> I've got a non-Rails project in which I'm using ERB.   I'd really like to
> duplicate Rails' "content_for" block/yield setup.  It wasn't hard to find
> the code that Rails uses for the content_for helper, but when I use it
> thusly:
>
> (child template)
> <% content_for :head do %>
>     <script>alert('test')</script>
> <% end %>
>
> (parent template)
> <%= yield :head %>
>
> I get an error when executing the parent template: (line nine is the one
> that contains the yield statement)
>
> (erb):9:in `get_binding': no block given (LocalJumpError)
>
> Obviously, I need to write a block that accepts the :head argument and
> returns the result stored in @content_for_head.  What I can figure our is
> where to pass that block into ERB.  The ERB.new class method does not
> accept a block (that I can see), neither does the ERB.result instance
> method.  My guess would be it's part of the context/binding I pass to ERB,
> but I've tried grepping the rails codebase and cannot find the place it sets
> this up.


Figured it out.  You don't pass a block to ERB, and you don't pass it to the
Kernel.binding call.  You do pass it to your own Context.get_binding method,
like so:

    erb_template.result(ctx.get_binding { |symbol| ctx.handle_yield(symbol)
})

There does not need to be any magic in the get_binding method:

  def get_binding
    binding
  end

-james

-- 
James A. Hillyerd <james at hillyerd.com>
Chief Technical Officer - ActiveRain Corp


More information about the Ruby mailing list