Ruby-on-rails Rails 从控制器渲染部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19360261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:52:02  来源:igfitidea点击:

Rails render partial from controller

ruby-on-railscontrollerpartial

提问by parov

I'm trying to render different partials into my index view from the controller, depending on the params I receive. I have a simple unless-else condition inside my controller that checks the params

我正在尝试从控制器将不同的部分渲染到我的索引视图中,具体取决于我收到的参数。我的控制器中有一个简单的unless-else条件来检查参数

def index
 unless params[:check].nil?
  render :partial => /layout/check
 else
  render :partial => /layout/not_check
 end
end

And I have the files _check.html.erb and not_check.html.erb into the folder layout/

我将文件 _check.html.erb 和 not_check.html.erb 放入文件夹 layout/

Now, how can I show that partials inside my index view? At the moment I can just visualize the partial alone as a single view, but not inside the requested view.

现在,如何在索引视图中显示该部分?目前,我只能将部分单独可视化为单个视图,而不是在请求的视图中。

采纳答案by techvineet

The better way would be to call the partials from index.html.erb

更好的方法是从 index.html.erb 调用部分

<% unless params[:check].nil? %>
  <%= render :partial => '/layout/check' %>
<% else %>
  <%= render :partial => '/layout/not_check' %>
<% end %>

so your def index would look like this

所以你的 def 索引看起来像这样

def index
  respond_to do |format|
    format.html
  end
end

I did not understand what you are trying to do but partial which are related to controller/actions should not be in layout unless they are serving some layout.

我不明白您要做什么,但是与控制器/动作相关的部分不应在布局中,除非它们提供某种布局。

回答by dax

If you're trying to render a layout (and not actual view information) try using render layout

如果您尝试渲染布局(而不是实际视图信息),请尝试使用渲染布局

def index
  if params[:check].nil?
    render layout: "not_check"
  else
    render layout: "check"
  end
end