Method: ActionView::Helpers::CaptureHelper#capture

Defined in:
lib/action_view/helpers/capture_helper.rb

#capture(*args) ⇒ Object

The capture method extracts part of a template as a String object. You can then use this object anywhere in your templates, layout, or helpers.

The capture method can be used in ERB templates…

<% @greeting = capture do %>
  Welcome to my shiny new web page!  The date and time is
  <%= Time.now %>
<% end %>

…and Builder (RXML) templates.

@timestamp = capture do
  "The current timestamp is #{Time.now}."
end

You can then use that variable anywhere else. For example:

<html>
<head><title><%= @greeting %></title></head>
<body>
<b><%= @greeting %></b>
</body>
</html>


37
38
39
40
41
42
43
# File 'lib/action_view/helpers/capture_helper.rb', line 37

def capture(*args)
  value = nil
  buffer = with_output_buffer { value = yield(*args) }
  if string = buffer.presence || value and string.is_a?(String)
    ERB::Util.html_escape string
  end
end