Home arrow Ruby-on-Rails arrow Page 4 - Web Development: Ruby on Rails
RUBY-ON-RAILS

Web Development: Ruby on Rails


Ruby on Rails has grown enormously in popularity over the last couple of years. This article, the first of a six-part series, will introduce you to its principles and show you how to use it. It is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Copyright © 2006 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
March 22, 2007
TABLE OF CONTENTS:
  1. · Web Development: Ruby on Rails
  2. · 15.1 Writing a Simple Rails Application to Show System Status
  3. · 15.2 Passing Data from the Controller to the View
  4. · 15.3 Creating a Layout for Your Header and Footer

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Web Development: Ruby on Rails - 15.3 Creating a Layout for Your Header and Footer
(Page 4 of 4 )

Problem

You want to create a header and footer for every page on your web application. Certain pages should have special headers and footers, and you may want to dynamically determine which header and footer to use for a given request.

Solution

Many web applications let you define header and footer files, and automatically include those files at the top and bottom of every page. Rails inverts this pattern. A single file called contains both the header and footer, and the contents of each particular page are inserted into this file.

To apply a layout to every page in your web application, create a file called app/ views/layouts/application.rhtml. It should look something like this:

  <html>
    <head>
      <title>My Website</title>
   </head>
    <body>
      <%= @content_for_layout %>
    </body>
  </html>

The key piece of information in any layout file is the directive <%= content_for_layout %>. This is replaced by the content of each individual page.

You can make customized layouts for each controller independently by creating files in the app/views/layouts folder. For example, app/views/layouts/status.rhtml is the layout for the status controller, StatusController. The layout file for PriceController would be price.rhtml.

Customized layouts override the site-wide layout; they don't add to it.

Discussion

Just like your main view templates, your layout templates have access to all the instance variables set by the action. Anything you can do in a view, you can do in a layout template. This means you can do things like set the page title dynamically in the action, and then use it in the layout:

  class StatusController < ActionController:Base
    def index
      @title = "System Status"
    end
  end

Now the application.rhtml file can access @title like this:

  <html>
   
<head>
     
<title>My Website - <%= @title %></title>
   
</head>
   
<body>
     
<%= @content_for_layout %>
    </body>
  </html>

application.rhtml doesn't just happen to be the default layout template for a Rails application's controllers. It happens this way because every controller inherits from ApplicationController. By default, a layout's name is derived from the name of the controller's class. So ApplicationController turns into application.rhtml. If you had a controller named MyFunkyController, the default filename for the layout would be app/views/layouts/my_funky.rhtml. If that file didn't exist, Rails would look for a layout corresponding to the superclass of MyFunkyController, and find it in app/views/ layouts/application.rhtml.

To change a controller's layout file, call its layout method:

  class FooController < ActionController:Base
    # Force the layout for /foo to be app/views/layouts/bar.rhtml,
    # not app/view/layouts/foo.rhtml.
    layout 'bar'
  end

If you're using the render method in one of your actions (see Recipe 15.5), you can pass in a :layout argument to render and give that action a different layout from the rest of the controller. In this example, most actions of the FooController use bar.rhtml for their layout, but the count action uses count.rhtml:

  class FooController < ActionController:Base
    layout 'bar'

    def count
     
@data = [1,2,3]
     
render :layout => 'count'
   
end
  end

You can even have an action without a layout. This code gives all of FooController's actions a layout of bar.html, except for the count action, which has no layout at all: it's responsible for all of its own HTML.

  class FooController < ActionController:Base
   
layout 'bar', :except => 'count'
  end

If you need to calculate the layout file dynamically, pass a method symbol into the layout method. This tells layout to call a method on each request; the return value of this method defines the layout file. The method can call action_name to determine the action name of the current request.

  class FooController < ActionController:Base 
    layout :figure_out_layout

    private

    def figure_out_layout
      if action_name =~ /pretty/
        'pretty'          # use pretty.rhtml for the layout
      else
        'standard'        # use standard.rhtml
      end
    end
  end

Finally, layout accepts a lambda function as an argument. This lets you dynamically decide on a layout with less code:

  class FooController < ActionController:Base
   
layout lambda { |controller| controller.logged_in? ? 'user' : 'guest' }
  end

It's freeing for both the programmer and the designer to use a layout file instead of separate headers and footers: it's easier to see the whole picture. But if you need to use explicit headers and footers, you can. Create files called app/views/layouts/_ header.rhtml and app/views/layouts/_footer.rhtml. The underscores indicate that they are "partials" (see Recipe 15.14). To use them, set your actions up to use no layout at all, and write the following code in your view files:

  <%= render :partial => 'layouts/header'
%>
  ... your view's content goes here ...
  <%= render :partial => 'layouts/footer'
%>

See Also
  1. Recipe 15.5, "Displaying Templates with Render"
  2. Recipe 15.14, "Refactoring the View into Partial Snippets of Views" 

Please check back next week for the continuation of this article.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
RUBY-ON-RAILS ARTICLES

- Adding Style with Action Pack
- Handling HTML in Templates with Action Pack
- Filters, Controllers and Helpers in Action P...
- Action Pack and Controller Filters
- Action Pack Categories and Events
- Logging Out, Events and Templates with Actio...
- Action Pack Sessions and Architecture
- More on Action Pack Partial Templates
- Action Pack Partial Templates
- Displaying Error Messages with the Action Pa...
- Action Pack Request Parameters
- Creating an Action Pack Registration Form
- Ruby on Rails Templates and Layouts
- Action Pack Controller Creation
- Writing an Action Pack Controller

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials