rails javascript helper - capturing an additional level of block nesting within a content_for

Posted by Tim Connor Thu, 08 Nov 2007 23:19:00 GMT

When making a helper that takes a block, the yield causes it to output at the point of being called in the template. If the reason for the helper is to populate a content_for/yield variable, such as to put javascript in the head tag, you get duplicate output: once where it belongs when the content_for is yielded, and once where you call your helper. Instead, make use of capture(&block).

This helper
  
def javascript(&block)
  content_for(:header) do
    "<script type=\"text/javascript\">//<![CDATA[#{capture(&block)}//]]></script>" 
  end
end
when called like this
 
<%javascript do%>
    alert('hi')
<%end%>
results inthis
<html>
<head>
<script type=\"text/javascript\">//<![CDATA[
alert('hi')
//]]></script>
if you have a yield :header in your head tag.
Comment form

(leave url/email »)

Help with Textile (code)