module Roger::Template::Helpers::Capture

The capture helper

Public Class Methods

included(base) click to toggle source
# File lib/roger/template/helpers/capture.rb, line 6
def self.included(base)
  # Just the writer; the reader is below.
  base.send(:attr_writer, :_content_for_blocks)
end

Public Instance Methods

_content_for_blocks() click to toggle source

rubocop:enable Lint/Eval

# File lib/roger/template/helpers/capture.rb, line 58
def _content_for_blocks
  @_content_for_blocks || {}
end
capture(&block) click to toggle source

rubocop:disable Lint/Eval

# File lib/roger/template/helpers/capture.rb, line 38
def capture(&block)
  unless Thread.current[:tilt_current_template].is_a?(Tilt::ERBTemplate)
    err  = "content_for works only with ERB Templates"
    err += "(was: #{template.current_tilt_template.inspect})"
    raise ArgumentError, err
  end

  @block_counter ||= 0
  @block_counter += 1
  counter = @block_counter

  eval "@_erbout_tmp#{counter} = _erbout", block.binding
  eval "_erbout = \"\"", block.binding
  t = Tilt::ERBTemplate.new { "<% return yield %>" }
  t.render(&block)
ensure
  eval "_erbout = @_erbout_tmp#{counter}", block.binding
end
content_for(block_name, &block) click to toggle source

Capture content in blocks in the template for later use in the layout. Currently only works in ERB templates. Use like this in the template:

“`

<% content_for :name %> bla bla <% end %>

“`

Place it like this in the layout:

“`

<%= yield :name %>

“`

# File lib/roger/template/helpers/capture.rb, line 23
def content_for(block_name, &block)
  @_content_for_blocks ||= {}
  @_content_for_blocks[block_name] = capture(&block)
end
content_for?(block_name) click to toggle source

Check if a block will yield content

“`

<% if content_for? :name %> bla bla <% end %>

“`

# File lib/roger/template/helpers/capture.rb, line 33
def content_for?(block_name)
  (!_content_for_blocks[block_name].nil? && !_content_for_blocks[block_name].empty?)
end