Partials in Sinatra

The ability to render partials (just a portion of the rendered output of a page) is an oft desired tool of a web framework, and Sinatra is no different. I still see a lot of people using a gisthttps://gist.github.com/lenary/119874 Sam Lenaryhttp://lenary.co.uk/ posted a while ago. Because I was using that a lot (and a few others) and copy and pasting them between projects I took it and put it in a gemhttps://rubygems.org/gems/sinatra-partial.

The gem comes with all the sugary goodness of:

  • documentation
  • specs
  • examples
  • fame and fortune to those who contribute to it
  • lies about fame and fortune
  • the warm glow that comes of helping others (along with attribution in the project files)

Sam and I have improved the code and the documentation a lot, so instead of duplicating effort and winding up with an old or inferior make of partial, give the gem a try. Here’s a quick example using a classic app:

require 'sinatra'
require 'haml'
require 'sinatra/partial'

helpers do
  def run_ads
    "Get Sinatra Partial today!"

get "/" do
  haml :index


and the haml:

@@ layout   
%title An example
  = partial :header
    = yield
  = partial :footer

@@ index
  %p Hello, World!
  = partial :side

@@ header
%header{ role: "banner" }  
  %a.title{ href: uri("/"), title: "example.org", rel: "index" }
  = partial :nav

@@ side
    = run_ads
    %ul= list_of Articles.get_related do |article|
      %a{ href="/articles/#{article.slug}" }= article.title
@@ nav
  = list_of(["Home", "About", "Contact", "FAQ"], {class: "nav", role: "nav"}) do |item|
    %a{ href: "/#{item.downcase}" }= item

@@ footer
  © 2013, Iain Barnett
Added on:
Last updated: