Module: Padrino::Helpers::RenderHelpers

Defined in:
padrino-helpers/lib/padrino-helpers/render_helpers.rb

Overview

Helpers related to rendering within templates (i.e partials).

Instance Method Summary collapse

Instance Method Details

#partial(template, options = {}, &block) ⇒ String Also known as: render_partial

Note:

If using this from Sinatra, pass explicit :engine option

Render a partials with collections support.

Examples:

partial 'photo/item', :object => @photo
partial 'photo/item', :collection => @photos
partial 'photo/item', :locals => { :foo => :bar }
partial 'photo/item', :engine => :erb

Parameters:

  • template (String)

    Relative path to partial template.

  • options (Hash) (defaults to: {})

    Options hash for rendering options.

Options Hash (options):

  • :object (Object)

    Object rendered in partial.

  • :collection (Array<Object>)

    Partial is rendered for each object in this collection.

  • :locals (Hash) — default: {}

    Local variables accessible in the partial.

  • :engine (Symbol)

    Explicit rendering engine to use for this partial.

Returns:

  • (String)

    The html generated from this partial.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'padrino-helpers/lib/padrino-helpers/render_helpers.rb', line 33

def partial(template, options={}, &block)
  options = { :layout => false }.update(options)
  explicit_engine = options.delete(:engine)

  path, _, name = template.to_s.rpartition(File::SEPARATOR)
  template_path = path.empty? ? :"_#{name}" : :"#{path}#{File::SEPARATOR}_#{name}"
  item_name = name.partition('.').first.to_sym

  items, counter = if options[:collection].respond_to?(:inject)
    [options.delete(:collection), 0]
  else
    [[options.delete(:object)], nil]
  end

  locals = options.delete(:locals) || {}
  items.each_with_object(SafeBuffer.new) do |item,html|
    locals[item_name] = item if item
    locals["#{item_name}_counter".to_sym] = counter += 1 if counter
    content =
      if block_given?
        concat_content(render(explicit_engine, template_path, options, locals) { capture_html(&block) })
      else
        render(explicit_engine, template_path, options, locals)
      end
    html.safe_concat content if content
  end
end