Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Helpers instead of Partials

I guess my rule of thumb is to use a helper to build a single "unit" of display -- like a span containing a link -- and to use a partial to build a more complex unit of display composed of more than one "unit" of display -- like a grid or a menu.


A partial is a view fragment, a piece of a view that is useful in multiple places and is pulled out so as to remove duplication. Bottom line, however, is that views - standalone or partial - are for presentation.

As you know, controllers are for processing logic. It is inevitable, however, that you will need some logic processing when presenting a view. So, for instance, if you have some presentation piece that is only available to admins, you might extract that logic to a helper and keep the view "pure" and presentation-only. Helpers will inevitably contain presentation code - html tags and such - but that is a by-product of their use, not their primary function.

You can also combine the two - a partial for the admin presentation and another for the user presentation, and a helper with the logic to determine which one is rendered in a particular situation.

Just my $.02.


The other answers represent the conceptual consensus regarding the use of helpers vs. partials. Consider the following for further reading:

Basecamp dev making the case for minimizing HTML in helpers http://37signals.com/svn/posts/1108-what-belongs-in-a-helper-method

Viget dev benchmarked each and found that helpers are faster than partials http://www.viget.com/extend/helpers-vs-partials-a-performance-question/


I use helpers when the code is likely to be used again in other projects, and partials for code specific to the project.


I use partials as subtemplates (i.e., something with lots of markup that gets used again and again, like a blog post blurb), and helpers to handle display more logic-y things (a div that's only visible to admins, for instance).