Assign a rendered partial to an instance variable

早过忘川 提交于 2019-12-21 11:34:07

问题


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


回答1:


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



回答2:


you are looking for render_to_string



来源:https://stackoverflow.com/questions/23626489/assign-a-rendered-partial-to-an-instance-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!