Take the 2-minute tour ×

I was wondering if I could execute / display some stuff differently in partials depending on the context in which it appears.

For example, I have a _user_info partial that appears in a sidebar, and also in the user page, and I want to display some extra info in the second case. How can I express that kind of conditions?

share|improve this question
add comment

4 Answers

up vote 2 down vote accepted

What you're asking for is something this:

if params[:controller].eql?('users')
  view code

However I would split the partial into two separate partials and display the distinct parts from whichever view you need.

share|improve this answer
Great, so I could just filter by controller or / and action, right? –  agente_secreto Sep 17 '11 at 14:12
Yes, you could condition however you want. –  mark Sep 17 '11 at 14:54
add comment

You can use controller_name and action_name methods.

if controller_name == 'user' && action_name == 'show'
share|improve this answer
add comment

Sure, it just depends on how you want to discover/expose that context. The simple way is conditionals, which can be set in any number of ways, or derived from a set of conditions. That can happen in a filter, an action, etc.

If the changes are large enough, better to just encapsulate them in separate partials.

Another option is to wrap the render tag in a helper that calculates/grabs those conditions.

It kind of depends on the nature of the conditions, where/how you want to deal with them, etc.

share|improve this answer
They are very small changes, like displaying the user avatar in a larger size for the user page, so I believe that for this case it's better to adhere to DRY and not creating and maintaining two separate partials... So I would just call my user avatar method with different parameters, what do you think would be the best option? –  agente_secreto Sep 17 '11 at 14:10
Some tiny changes are better off inline (IMO). Some people abstract all that kind of stuff into helpers; I think there's a point of diminishing returns, but I see their point. Once they're not tiny, it definitely makes sense to turn them into helpers, or additional partials. Where you draw that line is often just personal preference. –  Dave Newton Sep 17 '11 at 14:12
add comment

Or pass a variable into the partial via :locals =>

share|improve this answer
add comment

Your Answer


