Ruby on Rails content_for
April 24th, 2008
One of the mantras in the Rails community is DRY (Don't repeat Yourself), this is nothing new if your a software developer you should always look for ways to refactor your code to avoid copy and paste. Trying to maintain code with logic that has been copied and pasted to different locations is a nightmare, and one that unfortunately most of us have been exposed too.
In Rails the view part of MVC is handled by ActionView and the default templates are ERb. The views are further broken down into layouts and views. Layouts are called first for each controller then the view corresponding to the action. For the most part the layout is going to contain header elements for the xml, but what if you need some special javascript in one of you actions but not others.
You could just add it to the layout and say tough you are going to have the client load it no matter what, besides taking up extra bandwidth this can cause javascript errors for things like Google Maps where there is no associated div.
Rails gives you a better way though, you can use content_for to specify content associated with a particular yield command. For example if you wanted to use YM4R (Yellow maps 4 Ruby) to helps with your Google Maps mashup project, you could do something like this:
You would add a yield item to your layout.1 2 3 4 5 6 |
<head>
<%= stylesheet_link_tag :all %>
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag "popup" %>
<%= yield :head %>
</head> |
1 2 3 4 |
<% content_for :head do %> <%= GMap.header %> <%= @map.to_html %> <% end %> |
1 2 3 4 |
@map = GMap.new("map_div") @map.control_init(:large_map => true,:map_type => true) @map.center_zoom_init([75.5,-42.56],4) @map.overlay_init(GMarker.new([75.6,-42.467],:title => "Hello", :info_window => "Info! Info!")) |
That's it, your layout stays DRY and your single view gets the Google Map.



August 21st, 2008 at 04:54 PM Of all the tutorials on content_for I have found, yours explained it the easiest for me. Thanks!
August 21st, 2008 at 04:54 PM Of all the tutorials on content_for I have found, yours explained it the easiest for me. Thanks!
March 22nd, 2009 at 03:15 PM Thanks. This was very instructive. I just started learning Ruby/Rails and am having the time of my life! -Joe