rhys97
rhys97

Reputation: 81

Query about calling instance variables in view

I'm calling the following in my application.html.erb view layout

<%= @time %>

And this is what's in my application controller:

def time_now
@time = Time.current
end

Yet the time is not displaying on my browser. Any helps?

Thanks

Upvotes: 0

Views: 56

Answers (3)

nimrodm
nimrodm

Reputation: 23779

Are you sure you are calling the method time_now somewhere in your, say, index method?

E.g., try the following in your application controller (and make sure no one is overriding this method in a subclass:

def index
  @time = Time.current
end

So if your config/routes.rb has a root 'welcome#index', make sure the WelcomeController does not have an index method or is calling super so that the ApplicationController#index method is called to set @time.

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118261

You should definitely look into the content_for method. This is the tool will help you. As documentation said - simple content can be passed as a parameter.

So, simply put inside application.html.erb file.

<!DOCTYPE html>
<html>
  <head>
    <title>SamplAdmin</title>
  </head>
  <body>
    <%= content_for :time %>

    <%= yield %>

  </body>
</html>

Then pass the content from the view. I passed from index.html.erb file as :

<p id="notice"><%= notice %></p>
<% content_for :time, @time %>

Here is the simplified controller :

class UsersController < InheritedResources::Base

  def index
    @time = Time.now
  end
end

Upvotes: 0

Nikola Todorovic
Nikola Todorovic

Reputation: 310

Try this:

@time = Time.now

But you can also do this in your view, without controller:

<%= Time.now %>

Upvotes: 0

Related Questions