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

Using Haml with Sinatra


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
# 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
# This method shows you how to inject
# local variables
get '/goodbye/:name' do|name|
  haml :goodbye, :locals => { :name => name }
@@ layout
    %title Haml on Sinatra Example
@@ index
  %h1 Haml on Sinatra Example
    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.