content_for in Rails

Tuesday 11/18/2008  –  Category: Uncategorized

I'm not sure why I hadn't come across this before, but Rails has a nifty helper called content_for that allows you to insert stuff anywhere in your layout.

A classic use case is inserting a javascript source file that is only used on a specific page.

In your view:

<% content_for :head do %>
  <%= javascript_include_tag 'whatever.js' %>
<% end %>

In your layout:

<head>
  <title>Hello World</title>
  <%= yield :head %>
</head>

One Response to “content_for in Rails”

  1. Nick Zadrozny Says:

    Yeah, that one is awesome. The best part about it is you can use multiple blocks, so you can put your stylesheets in the :head and all your javascripts in a :foot block :-)

Leave a Reply