Flexible Templating/Layouts With Rails

Rails’ layout mechanism follows the standard pattern embodied in Sun’s J2EE patterns and familiar to users of Struts and other frameworks. The page template outputs the main content, and it’s automatically wrapped by a generic template (as opposed to the earlier SSI-style paradigm, where each page manually includes headers, footers, etc.). There’s always a complication with this pattern, which is that the page author usually wants to influence some aspects of the wrapping as well.

For instance, you’re writing books.rhtml for an E-Commerce site. You’re obviously going to set the main content – a list of books – but you also want to influence the wrapping, such as: change the page title (in the doc head), highlight “books” in the side menu, etc.

With many frameworks, you have to jump in to an XML file to influence the wrapping, which often means no-one bothers, and usability – not to mention search engine optimisation – suffers as a result…all pages end up with the same title and meta-information, and you’re probably downloading extra Javascript because you’ve made it the same for all pages.

Rails makes it quite easy, and being Rails, there’s no funny config files to mess with…it’s all code. The layout template is parsed after the main content, so the main content can set any variables, and the layout template can make use of them.

For example, standard-layout.rhtml says:

  1. <html>
  2.  
  3. <head>
  4.     <title><%= @page_title || "My App" %></title>
  5. </head>

Then, each page gets to choose its own title, e.g. books.rhtml:

  1. <% @page_title="Book Bargains" %>
  2.  
  3. <!-- Main content for books -->
  4. <h1>Lots of Books Today!</h1>
  5. ....

It’s easy to make Javascript (and CSS) flexible. The main layout loops through each specified script:

  1. <% (@scripts||&#91;&#93;).each do | script | %>
  2.     <script type="text/javascript" src="/javascripts/<%= script %>.js"></script>
  3. <% end %>

(Some people might prefer Rails’ script_include tag instead of manual script tags.)

Then, the page can optionally indicate the Javascripts it needs

  1. <% @page_title="Book Bargains" %>
  2. <% @scripts = &#91;"dojo", "util", "books"&#93; %>
  3.  
  4. <!-- Main content -->

2 thoughts on Flexible Templating/Layouts With Rails

Leave a Reply