In this tenth part of a multi-part series on the Action Pack library for Rails, you'll learn what partials are and how they can save you a lot of time and effort. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Action Pack Partial Templates - Automatic Local Variable Assignment in Partials (Page 2 of 2 )
Partials are distinct by virtue of a convenience convention: the value of an instance vari able with the same name as the partial will be available to the partial as a local variable. So, if you have a partial named _albums and an instance variable named @albums , youíll get a local variable called albums inside the partial.
Our form example doesnít do a very good job of illustrating this feature. Consider instead the following example, where we have all the necessary ingredients: an instance variable and a partial, both named articles .
class ArticlesController < ApplicationController def index @articles = Article.find(:all) end end
Hereís a list template ( app/views/articles/list.rhtml ) that renders the _ articles partial:
And hereís the _articles partial ( app/views/articles/_articles.rhtml ):
<ul> <% for article in articles %> <li><%= article.title %></li> <% end %> </ul>
The @articles instance variable that was initialized in the index action is available in the partial as the local variable articles because the partial is named articles . See the pattern here?
This behavior might seem a little too magical for purists, but itís a great example of how Rails goes out of its way to save you the tedium of implementing common patterns. Still, for the purists among you, and for those rare occasions when you need to use con figuration over convention, Rails makes it possible to explicitly set local template variables.
Please check back for the next part in this series.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.