Aswin Ramakrishnan
Aswin Ramakrishnan

Reputation: 3213

Rails: Rendering a template not showing Instance Variabe values

I'm trying to render a template that sits within another controller in a page. For some reason, the instance variable values aren't showing up in the page where I have the render. Although, it does show up when I go to the corresponding HTML page.

I'm pretty new to Rails, and maybe I'm missing something obvious with render. Here is some information -

This is the template I have as template.html.erb.

<a href="http://test.com" target="_blank">
    <div class="panel">
      <div>
        <img src="http://someimage" />
      </div>
      <div class="title">
        <%= @title %>
      </div><div class="text"><%= @text %></div>
    </div>
</a>

This is the corresponding method inside the controller - content_controller.rb:

def template
   @title = 'Test Title'
   @text = 'Test Content'

   respond_to do |format|
      format.html
   end
end

I'm trying to render it inside a page.html.erb this way -

render :template => 'content/template'

I can see the values of @title and @text if I navigate to content/template.html but not when I go to page.html

It would be great if somebody can help me out.

Upvotes: 0

Views: 255

Answers (2)

Aswin Ramakrishnan
Aswin Ramakrishnan

Reputation: 3213

Thanks Mori for the answer. Here is what I did -

  1. Created a helper method called get_content in content_helper

    def get_content
        @title = 'Test Title'
        @content = 'Test Content'
    end
    
  2. I called the get_content method from the page action

    include ContentHelper
    
    def page
      get_content
    end
    

Upvotes: 0

Mori
Mori

Reputation: 27789

Does the route that serves page.html go through the same template action as the content/template.html route? If not, that's the problem. The instance variables get initialized in that action, so if page.html doesn't use it, that explains what you're seeing.

Upvotes: 1

Related Questions