Capture lets you extract parts of code which can be used in other points of the template or even layout file.

Capturing a block into an instance variable

  <% @script = capture do %>
    [some html...]
  <% end %>

Add javascript to header using content_for

content_for("name") is a wrapper for capture which will make the fragment available by name to a yielding layout or template.

layout.rhtml:

  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
      <title>layout with js</title>
      <script type="text/javascript">
        <%= yield :script %>
    </script>
  </head>
  <body>
    <%= yield %>
  </body>
  </html>

view.rhtml

  This page shows an alert box!

  <% content_for("script") do %>
    alert('hello world')
  <% end %>

  Normal view text
Show files where this module is defined (1 file)
Register or log in to add new notes.