Capturing a block in ERB

Hi all,

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

<%= wrapper do %>

<%= content_tag(:span, "Hello World") %>
<% 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 => "


<%= content_tag(:span, “Hello World”) %>
"

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,

On Thu, Sep 23, 2010 at 9:58 AM, Gerold Böhler [email protected]
wrote:

and this in the helper

"

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 %>

<%%= content_tag(:span, "Hello World") %>
<% end %>

result = capture(&block)
result => "


<%= content_tag(:span, “Hello World”) %>
"

Best,
jeremy

Hi Jeremy,

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

<% wrapper do %>

<%= my_view_helper %>
<% 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

Am 9/23/10 8:16 PM schrieb “Jeremy K.” unter [email protected]:

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 %>

<%= my_view_helper %>
<% 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

Am 9/23/10 8:40 PM schrieb “Jeremy K.” unter [email protected]:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs