Using Layouts in Sinatra
Templating is a beautiful way to keep your code as DRY as possible. Many Ruby-based web frameworks allow you to create templates (called ‘layouts’) that can be used by many (or all) views in your application, and Sinatra is no exception.
The following code snippets demonstrate how to create a common layout which is reused in each view. Haml is used for HTML templating:
1 # main.rb 2 require 'rubygems' 3 require 'sinatra' 4 5 get '/' do 6 haml :index, :layout => :default 7 end 8 9 get '/about' do 10 haml :about, :layout => :default 11 end
Ok there is the setup. Pretty easy, right? Now we just have to create our ‘default’ layout and the 2 views as well:
1 # default.haml 2 !!! 3 %html{ html_attrs } 4 %head 5 %title My Awesome Ruby App 6 %body 7 = yield
That’s the layout file. Now the individual views’ code will be injected into the yield section. Here are simple examples of the 2 views, each one rendering a different paragraph.
1 # index.haml 2 %p This is my index page. Yay! 3 4 # about.haml 5 %p See how both of my views have the same base html? That's awesome!
The simplicity of implementation makes writing apps in Sinatra a blast.
Until next time!
