Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a rendered partial to an instance variable

In rails 4, I want to render a partial (say the footer) on anywhere of a page.

In home_controller.rb, I have this within a class:

def spree_application
 @test = render :partial => 'spree/shared/footer'
end

When I go to the index page and added:

<%= @test %>

Nothing happens. I know I can render within the index page but Im asking if there is a way to assign the rendered link to a variable.

Thanks!

Edit: I have made a mistake with this question. I have defined: spree_application

like image 389
Sylar Avatar asked May 13 '14 08:05

Sylar


2 Answers

you are looking for render_to_string

like image 97
antpaw Avatar answered Sep 29 '22 13:09

antpaw


Controller's render method is different than view's one. You want to execute it in a view context:

 @test = view_context.render 'spree/shared/footer'

The main difference between this method and render_to_string is that this returns html_safe string, so html tags within your <%= @test %> won't be escaped.

UPDATE:

However this is not the proper way of dealing with your problem. You are looking for 'content_for'. This method allows you to build part of the view, which can be used within the layout. All you need to do is to modify your layout:

# Your application layout
<html>
  <head>
  ...
  </head>
  <body>
    yield :image
    <div id="wrapper">
      yield
    </div>
  </body>
</html>

Then within your view, you can specify what is to be displayed as yield :image with

<% content_for :image do %>
  <%# Everything here will be displayed outside of the wraper %>
<% end %> 
like image 28
BroiSatse Avatar answered Sep 29 '22 11:09

BroiSatse