Module: Sinatra::Partial::Helpers

Defined in:
lib/sinatra/partial.rb

Instance Method Summary collapse

Instance Method Details

#partial(partial_name, options = {}) ⇒ String

Renders a partial to a string.

Examples:

simply render a partial

partial(:meta, :locals => {meta: meta})
  # => renders views/_meta.haml

render a partial in a subfolder

partial("meta/news", :locals => {news: [<News>]})
  # => renders views/meta/_news.haml

render a collection of objects with one partial

partial(:"meta/news", :collection => [<News>])
  # => renders views/meta/_news.haml once per item in :collection,
        with the local variable `news` being the current item in the iteration

Parameters:

  • partial_name (#to_s)

    The partial to render.

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

    The options to render the partial with.

Options Hash (options):

  • :locals (Hash)

    Local variables to render with

  • :collection (Array)

    Renders the template once per object in this array.

  • :template_engine (Symbol)

    The template engine to use. Haml by default.

  • :underscores (true, false)

    Set to true if you wish to follow the Rails convention of partial files having a leading underscore.

Returns:

  • (String)

    The rendered template contents.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/sinatra/partial.rb', line 57

def partial(partial_name, options={})
  options.merge! :layout => false
  partial_location = partial_name.to_s
  engine = options.fetch(:template_engine, settings.partial_template_engine)
  underscores = options.fetch(:underscores, settings.partial_underscores)
  
  template = Private.partial_expand_path(partial_location, underscores)
  
  if collection = options.delete(:collection)
    member_local = Private.partial_local(partial_location)
  
    locals = options.fetch(:locals, {})
  
    collection.inject([]) do |buffer, member|
      new_locals = {member_local => member}.merge(locals)
      buffer << self.method(engine).call(template, options.merge(:locals => new_locals))
    end.join("\n")
  else
    # TODO benchmark this and see if caching the method
    # speeds things up
    self.method(engine).call(template, options)
  end
end