Topic: How to make an instance variable available in all templates

Hello,

I am trying to setup a @user_logged_on variable that all templates can look at and use to choose what content to display.  I've already separated things out into different layouts for "visitor" and "user" as much as I can, but there are certain things, like putting a (login, logout, signup, already logged in... list underneath the page banner) that seem to require the templates to display information conditionally.

I would think to put it in the ApplicationController, but I'm not sure how.  I'm also a little bit worried that this might not be the best OO / MVC style.  If there's a better way please let me know.

Thanks a lot,
-xdotcommer

Re: How to make an instance variable available in all templates

I place conditional rendering into my helpers.

acts_as_authenticated makes the current_user method available to the controller, views and helpers. It just returns the current logged in user, if any. I used that to create small link methods in helpers, such as...

  def message_user_link(user, text="Message #{user.name}")
    unless(user == current_user)
      link_to(text, { :controller => 'post_office', :action => 'compose_message', :id => user })
    end
  end

So then whenever I need a link to send a user a message, I just use that method and don't think about it. It correctly determines if that link really should be created or not (ie, you shouldn't be able to send messages to yourself). My views have no conditionals in them and are dead easy to understand.

It has the added benefit of DRYing up link_to calls, all my message links are consistent and changed at one location if need be.

Whether it's really the best way, I don't know. But it's worked very well for me.

Last edited by tortoise (2006-12-17 11:15:36)

Re: How to make an instance variable available in all templates

Thanks, helpers seem to be what I was overlooking.
They should save me a few partials and get rid of some redundancy of rhtml I had.

-xdotcommer