Partials in HAML with Sinatra
Posted Mon, 25 Oct 2010
In Sinatra, you invoke haml by simply calling 'haml' with your template name.
get "/" do haml :index endOn that note, Sinatra (or HAML, I haven't checked) will let you use layouts, too, something I found hardly documented. Layouts are a way to basically wrap your entire template in another template called 'layout.haml' by default - useful if you want every page to have the same structure. You can also define different layouts.
What I wanted was a simple layout with a header in a separate template. Here's what I did:
%html %head %title Hello! %body #header =haml :header, :layout => false #content =yieldThie 'yield' will invoke the original template called as 'haml :index', helping keep each page using the same layout. Additionally, I render the header by calling a separate haml template; calling haml with ':layout => false' tells it to ignore any layout files. This lets us invoke another haml template.
Also, since the 'haml' method only takes symbols, if you want to put your haml templates in different directories, you'll have to use this awkward syntax:
haml :"some/path/to/template" # ^ Note the ':' before the string. You can also probably the # String#to_sym method.