将呈现的部分分配给实例变量 [英] Assign a rendered partial to an instance variable

查看:48
本文介绍了将呈现的部分分配给实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 rails 4 中,我想在页面的任何地方呈现部分(比如页脚).

在 home_controller.rb 中,我在一个类中有这个:

def spree_application@test = 渲染:部分 =>'狂欢/共享/页脚'结尾

当我进入索引页面并添加:

<%= @test %>

什么都没发生.我知道我可以在索引页面内呈现,但我问是否有办法将呈现的链接分配给变量.

谢谢!

我在这个问题上犯了一个错误.我已经定义:spree_application

解决方案

Controller 的 render 方法与视图的方法不同.您想在视图上下文中执行它:

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

此方法与 render_to_string 的主要区别在于它返回 html_safe 字符串,因此 <%= @test %> 中的 html 标签不会被转义.

更新:

然而,这不是处理问题的正确方法.您正在寻找content_for".此方法允许您构建可在布局中使用的视图的一部分.您需要做的就是修改您的布局:

#你的应用程序布局<头>...<身体>产量:图像<div id="包装器">屈服

</html>

然后在您的视图中,您可以使用

指定要显示为 yield :image 的内容

<% content_for :image do %><%# 这里的所有内容都将显示在包装器之外 %><%结束%>

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

解决方案

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

这篇关于将呈现的部分分配给实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆