Capturing a block in ERB

Hi all,

i have the following code as an erb template in rails 3:

<%= wrapper do %>
  <div>
    <%= content_tag(:span, "Hello World") %>
  </div>
<% end %>

and this in the helper

def wrapper(&block)
...
end

Now i would like to be able to capture the block into a variable
without parsing it:
result = capture_without_parsing(&block)
result => "<div>
    <%= content_tag(:span, "Hello World") %>
  </div>"

Is that even possible? I've been looking around for some time and
found some suggestions using ruby2ruby or serialize the block in some
other ways but they all have their flaws... Any help would be greatly
appreciated!

Regards,
Gerold

Hey Gerold,

Hi all,

i have the following code as an erb template in rails 3:

<%= wrapper do %>
<div>
<%= content_tag(:span, "Hello World") %>
</div>
<% end %>

and this in the helper

def wrapper(&block)
...
end

Now i would like to be able to capture the block into a variable
without parsing it:
result = capture_without_parsing(&block)
result => "<div>
<%= content_tag(:span, "Hello World") %>
</div>"

Is that even possible? I've been looking around for some time and
found some suggestions using ruby2ruby or serialize the block in some
other ways but they all have their flaws... Any help would be greatly
appreciated!

You can escape your ERB tags within the block:

<%= wrapper do %>
<div>
<%%= content_tag(:span, "Hello World") %>
</div>
<% end %>

result = capture(&block)
result => "<div>
<%= content_tag(:span, "Hello World") %>
</div>"

Best,
jeremy

Hi Jeremy,

Thanks for the quick reply! Let me explain my problem better:

<% wrapper do %>
<div>
  <%= my_view_helper %>
</div>
<% end %>

This is the view for a action. I need to be able to render this as usual and
i also need to be able to capture the block. Both times the template should
look like my example.

For the one case where i need the block as a string i could just use <%% as
you suggested. For the case where i need to render the file as usual i
suppose i could read the template, replace the <%% with <% and render that -
but for some reason i don't like doing that :slight_smile:

Regards,
Gerold

You could also just show the <%%= when you render the file itself :slight_smile:

(The way ERB compiles the template prevents you from getting the
"source" of a block directly.)

jeremy

:slight_smile: i suppose i could to that but then i still have a problem:

<% wrapper do %>
  <div>
    <%= my_view_helper %>
  </div>
<% end %>

The <% for the wrapper needs to stay but the <%'s inside the wrapper should
be replaced.

I understand this is a very specific problem and i am probably the only one
who has this problem - which should make me think i know - but i need it to
work this way. Of course if you tell me that it is not possible at all i
have to find a different solution :slight_smile:

Best,
Gerold