Instance variables in layouts

There’s probably a simple answer to this simple problem, but I am trying
to figure out how to reference an instance variable within a layout. In
the controller, one method corresponds to a view of the same name. Those
instance variables in the method can be used in the corresponding view.
However, I want my instance variable to be accessible throughout all my
views, not just one, without having to set the instance variable in each
method. Any solutions? Thanks!

-Gilles

If you have an attribute accessor on your controller, then you can
simply invoke the attribute accessor to read the controller instance
variable:

In the controller:

 attr_accessor :foo, :bar

Or simply

 def get_myvar
     return @myvar
 end

The controller is an instance variable of your view. You can read the
controller’s instance variables from inside your view with something
like

@controller.get_myvar

or

@controller.foo

I’ve just been playing around with this myself at
http://robmela.com/stupidtricks/introspection

There was also a useful thread back in June on instance variables in
controllers.

Gilles wrote:

However, I want my instance variable to be accessible throughout all my
views, not just one, without having to set the instance variable in each
method. Any solutions? Thanks!

Would this work for you?

before_filter :init

def init
@myvar = … #whatever you want here
end

init will run before any action is invoked, so I think it should be
available in your layout regardless of which action was called.

Jeff
softiesonrails.com

Jeff C. wrote:

Gilles wrote:

However, I want my instance variable to be accessible throughout all my
views, not just one, without having to set the instance variable in each
method. Any solutions? Thanks!

Would this work for you?

before_filter :init

def init
@myvar = … #whatever you want here
end

init will run before any action is invoked, so I think it should be
available in your layout regardless of which action was called.

Jeff
softiesonrails.com

And if you want all controller to have an instance variable put that
snippet in application.rb

And layouts works just like views.

<%= @myvar %> will work identically in both layouts and views. And
@myvar can be set in application.rb for all controllers in your whole
application via the above posters suggestion.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs