Ruby on Rails Layouts

Posted by jason on Jan 6, 2010 in Ruby |

Site wide layout

One common method of creating common look and feels in web development is to split up all the common code into a header file and a footer file and include those files in every single interface page.  This is better than embedding all that html code inside each page, but it is still clunky.  You can not easily see where your tags open and close because they can be opened in one file and closed in another file.  More advanced mechanisms put the overall code in one file but have middle sections where code specific html goes.  So, your html template file would look something like:

<html>
  <body>
    <%= yield %>
  </body>
</html>

It is easy to see the structure of an html page this way.  It also cleans up the code for your view.  Ruby on Rails implements this style of templating and calls it layouts.  Because of Rails’ convention over configuration, to implement a site wide template, you merely need to create /app/views/layouts/application.html.erb and put your site wide html code there.

Override default layout

You can override the layout that will be used by adding a layout declaration inside your controller class like this:

class HelloController < ApplicationController

  layout "mylayout"

  def index
  end
end

Create /app/views/layouts/mylayout.html.erb

Two different layouts, same view

You may have different layouts depending on whether the user is logged in or not.  This is easy to accomplish by using a symbol for the layout.

class HelloController < ApplicationController

  layout :isLoggedInLayout

  def index
  end

private
  def isLoggedInLayout
    "loggedIn"
  else
    "notLoggedIn"
  end
end

You would have two templates, one /app/views/layouts/loggedIn.html.erb, the other /app/views/layouts/notLoggedIn.html.erb.

Reply

Powered by WP Hashcash

Copyright © 2010 programming with passion All rights reserved. Theme by Laptop Geek.