Mr eel

Getting Fancy with Partials in Rails

Well! It’s been awhile since I’ve posted about Rails. Lots of urgent work has left me without time to work on my little side-projects, but now I’ve got a little breathing space I can get back into things.

Anyhow, I’ve found some interesting uses for partials. They’re really good for cutting down on template code. However, I have come across a few instances where I have needed the contents of the partial to be slightly different. Say I need a form to have one less input.

I’ve got the option of duplicating the partial and omitting that input, but that defeats the purpose of using partials. You will end up having to maintain two partials that are very close to one another. The answer my deal little space-monkeys is to exploit the :locals option in the #render method.

Normally if I want to render a partial, I might do something like this:

render(:partial => '_form')

But we can pass in some additional variables to the partial using the locals option:

render(:partial => '_form', :locals => {:omit_name => true})

What the :locals option does is pass whatever variables you give it to the partial. So now the partial _form will have access to the local variable omit_name.

This means we can pass in configuration options to the partial. Considering the render call above, we could have this corresponding code in the partial:

< % unless defined? omit_name %>
< %= text_field 'job', 'name' %>
< % end %>

Succinctly, this code says “If there is a local variable called omit_name don’t show this field”. You can see how this could be used to switch different bits of a partial on or off, making them just that bit more flexible.

One small suggestion however, I would avoid getting into situations where you are passing multiple bits of configuration to a partial. In that case you may actually be better off using multiple partials instead of just the one. Remember, minimise the code in your views!

Posted on December 7th, 2005 | There are 0 comments

Comments

Add a comment

All contents © 2005—2007 Luke Matthew Sutton