20

I'm new to Sinatra and I can't figure out where to put my application layout.

I've seen the inline method that uses

# app code    
__END__

@@layout
  %html
    = yield

But I'd like the layout to be in it's own .haml file.

What should the layout file be named? What directory should it be placed in?

maček
  • 76,434
  • 37
  • 167
  • 198

2 Answers2

27

Automatic Wrapping

To make every view default to be wrapped in a layout, create a file in views/layout.haml and your calls to haml :myview will automatically be wrapped in this layout.

Skipping the Layout

If you want a particular view rendering not to use the layout, use:

get '/' do
   # Other pages will use layout.haml, but not the main page
   haml :home, :layout => false
end

Using a Different Layout

If you want to use a layout other than the common layout, create another file (for example views/admin_layout.haml) and then pass this as an option:

get '/admin/create' do
   haml :create, :layout => :admin_layout
end
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • I'm getting this error `undefined local variable or method \`layout' for ` when I use the layout option, please help me – pahnin Jun 25 '12 at 13:02
  • it worked if I changed the ` - ` to underscore ` _ ` i.e, `admin_layout` please see this http://stackoverflow.com/questions/11190208/nameerror-in-using-custom-layout-option-in-sinatra-app – pahnin Jun 25 '12 at 17:28
  • 1
    @pahnin My mistake; thank you for pointing that out. FWIW if should work if you did `:layout => :"admin-layout"`, but better to simply use a name that is easily represented as a symbol literal. I have updated my answer. – Phrogz Jun 25 '12 at 17:42
20

If you haven't already, create a folder where your sinatra script lives called...

views/

and put your layout in there, call your layout

layout.haml

or whatever extension (e.g. .erubis) you'd like to use.

ocodo
  • 29,401
  • 18
  • 105
  • 117