can helpers manipulate block?

hi,

i'm unsure the best way to ask this but i'm wondering if a rails
helper can manipulate html. for instance if i had a helper that looked
like this:

<% my_helper do %>
  <br />
<% end %>

is there a way i can programatically work with the html content (i.e.
<br />)? is there a variable available in my helper that represents
the content between the helper and end tags?

thanks in advance, mike

Hi --

hi,

i'm unsure the best way to ask this but i'm wondering if a rails
helper can manipulate html. for instance if i had a helper that looked
like this:

<% my_helper do %>
<br />
<% end %>

is there a way i can programatically work with the html content (i.e.
<br />)? is there a variable available in my helper that represents
the content between the helper and end tags?

Yes; you could do it like this:

   def my_helper(&block)
     string = capture(&block)
     concat(do_something_to(string), block.binding)
   end

capture grabs the content from the template; concat inserts the
manipulated string into the output stream. You have to pass
block.binding along so that concat is operating in the right scope.

David

Michael Bannister wrote:

i'm unsure the best way to ask this but i'm wondering if a rails
helper can manipulate html. for instance if i had a helper that looked
like this:

<% my_helper do %>
<br />
<% end %>

is there a way i can programatically work with the html content (i.e.
<br />)? is there a variable available in my helper that represents
the content between the helper and end tags?

Unfortunately yes. Inside my_helper, use capture and yield. The return value of capture(yield), IIRC, is the HTML.

capture is sensitive to call because eRB mangles your HTML before evaluating it, and capture naturally sees the mangled version. Google for capture to see how to use it. Then use <%= my_helper, and return your version of the captured HTML.

And please reconsider. There's always a way to write the correct HTML the first time; you shouldn't want to search and replace inside it. For example:

<% my_helper do |creator| %>
   <br />
   <%= creator.create_html %>
   <br />
<% end %>

Now my_helper initializes a creator, and this creates more HTML and inserts it into the block. This is generally what blocks are for - to mix and match objects from outside the block (like eRB) with objects inserted into the block by the goal-posts operator ||.