Written by Sean Behan on Sun Oct 13th 2013

Sinatra doesn't have a method for rendering partials. It defers to the template language of your choice. For instance, if you're using ERB, it's as simple as

erb :'path/to/partial'

Rails has a nice convention of using an underscore to mark files as partials.

<%= render 'path/to/partial' %> 

Will resolve the path 'path/to/_partial'. But it's a little ugly to look at the underscore in the file path in your templates.

To get this same thing in Sinatra, you can wrap partial rendering in a helper function.

helpers do
  def partial(template, opts={})
    parts = template.split('/')
last = "_#{parts.pop}"

erb([parts, last].flatten.join('/').to_sym, {layout: false}.merge(opts))

end end

We can pass additional argument to the partial function if we want to use locals, for instance.

Tagged with..
#Sinatra #Ruby #Webapps

Just finishing up brewing up some fresh ground comments...