Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I yield from an ERB code block without rendering it?

Consider the following:

view.html.erb:

<%= make_backwards do %>
  stressed
<% end %>

helper.rb:

def make_backwards
  yield.reverse
end

The view renders stresseddesserts instead of just desserts. How do I use the content in yield without rendering the code block?

like image 210
Benjamin Cheah Avatar asked Dec 17 '13 08:12

Benjamin Cheah


1 Answers

ERB has an internal buffer, which makes using blocks a bit more complicated, as you can see in your code example.

Rails provides a capture method, which allows you to capture a string inside this buffer and return it from a block.

So your helper would become the following:

def make_backwards
  capture do
    yield.reverse
  end
end
like image 113
Damien MATHIEU Avatar answered Oct 08 '22 01:10

Damien MATHIEU