views:

45

answers:

2

I am trying to find a way to add content to a div that is defined in my application.html.haml file from individual view files. The reason I want to do this is because I have a sidebar that is always present and is defined in the template, but I would like to have content specific to each page included in the sidebar. Would this be done best with javascript or is there some ruby on rails trick that I can use to make this easier?

+3  A: 

I would use the content_for helper (Rails Guide) (API).

In haml, this would look something like:

(layout template)

#sidebar= yield :sidebar

(page template)

-content_for :sidebar do
  ...your content here
Greg Campbell
Thanks a ton! This is exactly what I need. Is there anyway to pass a partial to content_for?
Teddy
content_for takes a block (speaking of which, I noticed that I missed the "do" at the beginning of that block in my answer) - inside that block, you can do anything you would be able to do in a normal Haml template, including rendering partials, etc.
Greg Campbell
+1  A: 

If you work with professional designers who handle the views, it may be easier over the long term to have rather repetitive view code. Some people have a hard time searching through partials and "seeing" how they all fit together. I've found it easier with those people to let them manage the whole shebang and update more than one file if they need to. Optimal? Not to us as programmers, but designers are more often used to seeing most of the HTML in one or three files rather than 20. :)

use partials as much as possible to keep your code DRY

this link helps you

http://guides.rubyonrails.org/layouts_and_rendering.html

The first paragraph of this is copied from Ian Terell's answer [here](http://stackoverflow.com/questions/926761/best-practices-for-using-partials-in-rails/926941#926941). Now that's just rude.
sepp2k