[英]Render show view in a partial - Ruby on Rails
方法如下:
1)在您的布局中包含sidebar
部分 :
#app/views/layouts/application.html.erb
<%= render "shared/sidebar" %>
这会在/app/views/shared
调用_sidebar.html.erb
部分:
2)填充“默认”侧栏部分:
#app/views/shared/_sidebar.html.erb
...
这里要注意的重要一点是, @instance
变量中绝对不应包含@instance
变量。
部分对象具有locals
,您可以使用以下命令传递它们:
<%= render "shared/sidebar", locals: { variable: "value" } %>
局部变量可以在Web应用程序的任何部分上运行,并且由于@instance
变量存在于对象的单个“实例”中(IE @post
在/users
中将不可用),因此您可以确保始终填充@instance
变量通过将局部变量传递给他们。
这就是为什么将post#show
代码复制到sidebar
部分时会收到错误的原因-用于show
动作的实例变量将不会出现在应用程序的其他部分。
3)使用JS拉取图像对象
当某人单击网格中的图像时,我基本上希望将显示视图显示在侧栏中。
您需要更加具体-您是否真的要显示“显示”操作,还是想要部分功能?
无论哪种方式,最好使用JS和ajax提取数据:
#app/controllers/images_controller.rb
class ImagesController < ApplicationController
layout Proc.new { |controller| !controller.request.xhr? }
end
#app/assets/javascripts/application.js
$(document).on("click", "img", function(e) {
e.preventDefault();
$.get($(this).attr("href"), function(data){
$(".sidebar .image").html(data);
});
});
这将执行渲染的images#show
操作(不带布局),并将其附加到侧边栏部分。 这就是您要的-如果需要,我可以更改它。
假设您的模型称为“图片”。
在您的“ images / show.html.erb”中:
# This is a handy shortcut that will call the 'images/_image' partial.
# Those two lines are exactly the same.
<%= render @image %>
<%= render "images/image", image: @image %>
在您的“ _sidebar.html.erb”中:
<div id="sidebar-img"></div>
在您的“ images / _image.html.erb”中:
# Code displaying your image, don't use any global variable.
# 'image' is the name of the local variable
在您的网格中:
# remote: true allows you to do an AJAX call
<%= link_to image, remote: true do %>
# Something like that, I don't know your code
<%= image_tag image.url %>
<% end %>
创建“ images / show.js.erb”,单击“ remote:true”链接时,它将调用此文件。
# set @image to Image.find(params[:id]) in your controller
$("#sidebar-img").html("<%= render @image %>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.