1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Using Haml with Sinatra

By

7 of 7

Using Haml with Sinatra

Integrating Haml and Sinatra is trivial. Simply include the Haml gem, use Haml for your views, and call the haml method instead of the erb method. The following is an example of how to use Haml views in your Sinatra applications. It shows a layout, a normal view (the index view) and two ways to inject variables into your views.

#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'haml'
 
get '/' do
  haml :index
end
 
# This one shows how you can use refer to
# variables in your Haml views.
# This method uses member variables.
get '/hello/:name' do|name|
  @name = name
  haml :hello
end
 
# This method shows you how to inject
# local variables
get '/goodbye/:name' do|name|
  haml :goodbye, :locals => { :name => name }
end
 
__END__
@@ layout
%html
  %head
    %title Haml on Sinatra Example
  %body
    =yield
 
@@ index
#header
  %h1 Haml on Sinatra Example
#content
  %p
    This is an example of using Haml on Sinatra.
    You can use Haml in all your projeccts now, instead
    of Erb. I'm sure you'll find it much easier!
 
@@ hello
%h1= "Hello #{@name}!"
 
@@ goodbye
%h1= "Goodbye #{name}!"
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Sinatra
  6. Using Haml with Sinatra

©2014 About.com. All rights reserved.