0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, page.html is inside a different controller. It doesn't go through the template action. Should I call template action from the page action? Sorry, I'm new to Rails. Can you tell me if there is an elegant way to do this?
You just need to create the same instance variables in whatever controller action precedes the page.html.erb template. There are different ways to share the code that does that. But you can just repeat those @title = ... and @text = ... assignments in page's action.
0

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
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.