The ActionPack component has a feature called “Layouts” (docs here) which you use to “wrap” some presentation around your views.
To do that, update your controller with something like:
class FriendsController < AbstractApplicationController include FriendsHelper layout "standard"
Now, create “views/layouts/standard.rhtml” with the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>RailsTest: <%= @page_title %></title>
</head>
<body>
<div>The header part of this layout</div>
<div><%= yield %></div>
<div>The footer part of this layout</div>
</body>
</html>
Then, open your display.rhtml view for example (from the tutorial), and prune out the now-redundant tags and so-on, as they’re in this layout now.
You’ll notice the title tag has a variable reference, I just edited the list method in my controller to set it:
def list @page_title = "List Friends" @person = Person.find(1) end
Now, load the view. Voila – you should have a header and footer.
NOTE: If you have a layouts/application.rhtml this will get picked up automatically…no need tospecify it in the controllers…
To take layouts further, you can extract parts of your layout into individual files, and source them into your layout. This is done by using ActionView::Partials
A classic example of this having 2 pane and 3 pane layouts both sharing the same ‘header’, therefore avoiding redundancy:
<div id="header"><%= render_partial "layouts/header" %></div>
In this above example, the contents of ”_header.rhtml” in your layouts folder is sourced into the main layout. Pretty standard for website design/layout, and rails handles this nicely.
class WeblogController < ActionController::Base
layout :writers_and_readers
def index
# fetching posts
end
private
def writers_and_readers
logged_in? ? "writer_layout" : "reader_layout"
end
Comments:
Posted by Niklas 20:05 GMT, 22.04.08
Short but good…
category:Howto