Sylar Sylar - 22 days ago 4x
Ruby Question

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'

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.


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


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.


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
    yield :image
    <div id="wrapper">

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 %>