繁体   English   中英

局部渲染渲染视图-Ruby on Rails

[英]Render show view in a partial - Ruby on Rails

因此,我的rails应用程序中有一个侧边栏。 基本上,我有一个充满图像的网格。 当某人单击网格中的图像时,我基本上希望将显示视图显示在侧栏中。 我对如何做到这一点一无所知。

我尝试将show view的html和erb复制并粘贴到_sidebar.html.erb部分中。 但是我得到了可变错误。 我的部分位于我的布局文件夹中。 但是我可以根据需要移动它。

这是应用程序的图像,可以更好地了解我在说什么。

这就是我的应用程序的样子。灰色部分是侧边栏部分。

方法如下:


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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM