Rails 2.0 Patrials and Collections part2

// March 19th, 2009 // Rails

In part one of this article we went over how to create and use partials. Part two will take what we learned from part one and see how we can use collections to make partials even more useful. We’ll see how you can set additional local variables in your partial. This article is short and assume you have read part1 of this article.

Outline for this article

  1. How do we set local variables in Rails Partials?
  2. Using Rails Partials in a loop?
  3. Is there a point to the Spacer Template in Rails Partials?

How do we set local variables in Rails Partials?
Ok, so we know that we can pass in an object to a partial with the

 :o bject

symbol. Great, but what if you want to use more variables in the partial.
This can be done using the

:locals

symbol in the render helper. For example if go back to the example given in part1

<%= render :partial => "shared/testpartial", :o bject => @name , :locals => {:testvar => @any_object_you_want } %>;

Just make sure you know the name of the local variables you are setting.

Using Rails Partials in a loop?
With partials we can format create modular views. Sometimes you’ll find the need to
render a partial many time over. On way you can do this is to run the partial in a for loop.
Rails has a shortcut for this. You can use the symbol

:collection

The symbol takes a collection of objects that the partial takes! The example from part1 took a string object. So to use the collection we can pass it a list of string objects like the following

<%= render :partial => "shared/testpartial",
:collection => %w{ Mez Adam Azmara John} %>;

This is a very useful feature, if used correctly your views show look clean. This makes maintenance
of code very manageable and enjoyable.

Is there a point to the Spacer Template in Rails Partials?
There is a option the render helper can take called

:spacer_template

It lets you specify a template that will be rendered between each of the elements in the collection.
Basically, it renders another parital. Here is how to use it.

<%= render :partial =&gt; "shared/testpartial",
:collection => %w{ Mez Adam Azmara John},
:spacer_template => "shared/another_partial" %>;

Note, this assumes you have a “_another_partial.html.erb” handy. My thinking on this is a little off. I am not sure if you really need to define another partial to display in between partials. Why not just define the content of the spacer template in the first partial? Give some good examples if you think of any!

That concludes this article. I hope you enjoyed it!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Yahoo! Buzz

Leave a Reply

-->

Categories