3. Layouts
We want all the pages displayed from our demo site to have the same layout, i.e. same topbar, sidebar etc.
We can add layouts for the entire application or for individual controllers. Let us go with a global layout for now.
Let's add some debug info to our pages.
We can add layouts for the entire application or for individual controllers. Let us go with a global layout for now.
- Update demo/app/views/layouts/application.rhtml
<html>
<head>
<title><%= page_title %></title>
<%= stylesheet_link_tag 'scaffold' %>
<%= @head_elements %>
</head>
<body>
<p style="color: green"><%= flash[:notice] %></p>
<%= @content_for_layout %>
</body>
</html>
page_title is a helper method that we will add shortly. A controller can set an instance variable page_title which will be picked up by the helper method, or a default string will be provided.
head_elements is an instance variable that can be set by a controller or view template. This can be used to add for e.g. a auto-referesh tag for unknown_request.rhtml. We will do so shortly as well.
flash[:notice] is a string that can be used to display any messages generated by a controller.
@content_for_layout would be the content generated by the render method, for e.g. using the view template or it could be generated inline in the controller. - Add the layout name to app/controllers/application.rb so that all controllers can pick this layout.
class ApplicationController <>
layout "application"
end - Update app/helpers/application_helper.rb to add the page_title helper method
module ApplicationHelper
def page_title
@page_title || "Demo Website"
end
end
There, that should do the trick. Now all the web pages will share the same layout.
- Update app/views/index/unknown_request.rhtml to set the instance variable @head_elements :
<% @head_elements = '<meta http-equiv="refresh" CONTENT="10; URL=' + url_for(:action => "index") + '">' %>
<h1>Error: Page not found!</h1>
<p>Please click here to return to the <%= link_to("main", url_for(:action => "index")) %> page. Your browser will automatically redirect you there in 10 seconds.</p>
Let's add some debug info to our pages.
- Copy and paste DebugHelper model from here in demo/app/helpers/debug_helper.rb.
- Update demo/app/views/layouts/application.rhtml as shown below:
<html>
...
<%= debug_popup %>
</body>
</html>
- Add the helper declaration to app/controllers/application.rb
class ApplicationController < ActionController::Base
layout "application"
helper :debug
...
end - Refresh the browser. If it doesn't work, maybe you need to restart the webserver.

0 Comments:
Post a Comment
<< Home