Skip to content

Instantly share code, notes, and snippets.

@lenary
Created May 29, 2009 09:30
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 23 You must be signed in to fork a gist
  • Save lenary/119874 to your computer and use it in GitHub Desktop.
Save lenary/119874 to your computer and use it in GitHub Desktop.
# stolen from http://github.com/cschneid/irclogger/blob/master/lib/partials.rb
# and made a lot more robust by me
# this implementation uses erb by default. if you want to use any other template mechanism
# then replace `erb` on line 13 and line 17 with `haml` or whatever
module Sinatra::Partials
def partial(template, *args)
template_array = template.to_s.split('/')
template = template_array[0..-2].join('/') + "/_#{template_array[-1]}"
options = args.last.is_a?(Hash) ? args.pop : {}
options.merge!(:layout => false)
locals = options[:locals] || {}
if collection = options.delete(:collection) then
collection.inject([]) do |buffer, member|
buffer << erb(:"#{template}", options.merge(:layout =>
false, :locals => {template_array[-1].to_sym => member}.merge(locals)))
end.join("\n")
else
erb(:"#{template}", options)
end
end
end
@CarlosGabaldon
Copy link

I spent some time studying base.rb before making my implementation, and I considered using render directly, but it I personally did not like the idea of bypassing the built-in template rendering methods.

@lenary
Copy link
Author

lenary commented Apr 10, 2012 via email

@CarlosGabaldon
Copy link

Excellent! I will be switching my current project over to using the gem. Thanks for all of the great work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment