instance method capture

Ruby on Rails 7.0.10

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

capture(*args)

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>

The return of capture is the string generated by the block. For Example:

@greeting # => "Welcome to my shiny new web page! The date and time is 2018-09-06 11:09:16 -0500"

Parameters

args rest
Source
# File actionview/lib/action_view/helpers/capture_helper.rb, line 43
      def capture(*args)
        value = nil
        buffer = with_output_buffer { value = yield(*args) }
        if (string = buffer.presence || value) && string.is_a?(String)
          ERB::Util.html_escape string
        end
      end

Defined in actionview/lib/action_view/helpers/capture_helper.rb line 43 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::CaptureHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close