Jack Polgar

Partials in Sinatra

While working on my latest project, a Sinatra powered blog/cms I needed a way to render partials.

However the only code I could find was down right ugly.

I hate ugly code, I can’t stand it, so there was no way I was going to use this code.

This is where my second greatest piece of code for Sinatra was created.

Only 3 lines of code inside the method, 7 for the entire thing, is probably the best way to render partials in Sinatra.

#
# Sinatra Partials
# Copyright (C) 2011 Jack Polgar
#
# @copyright Jack Polgar 2011
# @license New BSD License
# @example:
#    render_partial 'articles/article', :article => article
#
helpers do
  def render_partial(template, args = {})
    template_array = template.to_s.split('/')
    template = template_array[0..-2].join('/') + "/_#{template_array[-1]}"
    erb(template.to_sym, :locals => args, :layout => false)
  end
end

Published on