Recipe: Page-Specific Content for the HTML Head Section

Rails layouts are a nice way to organize boiler-plate HTML content in a DRY ("Don't Repeat Yourself" in case you've been asleep for a while) fashion. But your standard layout may not be sufficient to meet the needs of all web pages, particularly when it comes to including CSS style sheets or JavaScript files.

The Problem

In a Rails 3.x application, how can you provide an easy method for web pages to include page-specific CSS style sheets and JavaScript files within the <head> section of the HTML?

The Solution

Here's a straight-forward solution to the problem:

   <!DOCTYPE html>
     <%= stylesheet_link_tag :all %>
     <%= javascript_include_tag :defaults %>
     %lt;%= csrf_meta_tag %>
     <%= yield :head %>

   <%= yield %>


Note the "yield :head" statement in the <head> section of the document. With this construct in place, any web page can add custom content to the <head> element of the page.

  <% content_for :head do %>
    <%= javascript_include_tag 'custom.css' %>
  <% end %>

In the example above, a custom CSS file is added for one specific web page.

With this method, no other page has to bear the burden of including a CSS file that will not be used on that page. For any page that does not provide content for the <head> element, well, no content will be inserted. This is a simple way to support per-page customization capabilities while only affecting the pages that need their own custom support files.


David Keener By dkeener on Wednesday, August 03, 2011 at 11:48 AM EST

To the extent possible, it's beneficial to limit the number of CSS stylesheets your web site has. So I'm not advocating tons of little CSS stylesheets for your web site. But when one page has a bunch of special-purpose CSS, it's good to segregate that code in a separate stylesheet and include it in only where it's needed.

The recipe described in this article serves to meet those occasional CSS needs.

Leave a Comment

Comments are moderated and will not appear on the site until reviewed.

(not displayed)