#8
Mar 21
Layouts and content_for
If you want to change something in the layout on a per-template basis, content_for is your answer! This allows templates to specify view code that can be placed anywhere in a layout.
<!-- projects/index.rhtml --> <% content_for :head do %> <%= stylesheet_link_tag 'projects' %> <% end %> <!-- layouts/application.rhtml --> <head> <title>Todo List</title> <%= stylesheet_link_tag 'application' %> <%= yield :head %> </head>



Thank you. Thank you. Thank you.
I don't like this method because you get two <link ... type="text/css" /> items in your HTML source.
I really don't think that this is an appropriate behavior.
@rs, that's a valid concern. However, I think it's acceptable if one page requires a lot of additional styling. No sense in putting all this styling in a global CSS file and requiring it on every other page. Also, if the users are coming from another page they will likely have the global "application.css" stylesheet cached.
hi,
what is the meaning of yield and :head in => <%= yield :head %>
The "yield" call in a layout will output the contents of the template. When supplying a parameter (:head in this case) it will output the contents of that content_for block. I explained this in the episode, sorry if it wasn't clear.
@rs and ryan,
it seems to me that having multiple <link.../> tags is like having multiple <script /> tags in the head. is there some rule that says multiple script tags are ok, but link tags for css should be in one file? eric meyer has 8 stylesheet links on his homepage (as of today). i think he knows what he's doing vis-a-vis css.
it's a fantastic little railscast, btw. these little tricks make dev so much easier and smarter. thanks for doing this! you're a mensch.
You can have multiple link tags. This is even used in the W3C standards to have multiple stylesheets specified for different medias, or simply to allow choice of stylesheets. (In Firefox, this shows up in the View Menu -> Page Style sub-menu.)
What is the best way and is there a best way to call a "content_for" between
<%=yield :mycontent %>
and
<%=@content_for_mycontent %>
kriom, there shouldn't be any difference, since content_for_mycontent is only old style version for yield in Rails, as far as I am concerned.
However, the reader should be careful to observe that the things in themselves stand in need to, even as this relates to our experience, our sense perceptions.
Wonderfull cast!