Module: SinatraHelpers::Erb::Partials

Defined in:
lib/sinatra_helpers/erb/partials.rb

Instance Method Summary collapse

Instance Method Details

#partial(template, options = {}) ⇒ Object

helper to emulate rails’ ‘render :partial’ helper, using erb

> taken from the sinatra book, sinatra-book.gittr.com/#implemention_of_rails_style_partials

Render the partial once: Usage: partial :foo

foo partial will be rendered once for each element in the array, passing in a local variable named “foo” Usage: partial :foo, :collection => @my_foos



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/sinatra_helpers/erb/partials.rb', line 16

def partial(template, options={})
  options.merge!(:layout => false)
  path = template.to_s.split(File::SEPARATOR)
  object = path[-1].to_sym
  path[-1] = "_#{path[-1]}"
  template = File.join(path).to_sym
  raise 'partial collection specified but is nil' if options.has_key?(:collection) && options[:collection].nil?
  if collection = options.delete(:collection)
    options.delete(:object)  # ignore any object passed in when using :collection
    options[:locals] ||= {}
    counter = 0
    collection.inject([]) do |buffer, member|
      counter += 1
      erb_opts = options.dup
      erb_opts[:locals].merge!({object => member, "#{object}_counter".to_sym => counter})
      buffer << erb(template, erb_opts)
    end.join("\n")
  else
    if member = options.delete(:object)
      options[:locals] ||= {}
      options[:locals].merge!({object => member})
    end
    erb(template, options)
  end
end