Rails:从视图内渲染视图(不是局部) [英] Rails: Render a View (not a partial) From Within a View

查看:45
本文介绍了Rails:从视图内渲染视图(不是局部)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个响应 htmljs 的控制器.html 视图呈现整个页面(包括页眉和页脚),而 js 仅替换 #main.除了页眉和页脚之外,两种格式呈现相同的内容.我可以用三个文件得到这个效果:

I have a controller that responds to both html and js. The html view renders the whole page (including the header and footer), while the js only replaces #main. Aside from the header and footer, both formats render the same content. I can get this effect with three files:

_show.html.erb
<div>Content!</div>

show.html.erb
<%= render "show" %>

show.js.erb
$("#main").fadeIn("<%= escape_javascript(render 'show') %>");

这可行,但如果我不需要单独的 _show 部分,我更喜欢.不幸的是,这不起作用:

This works, but I'd prefer if I didn't need a separate _show partial. Unfortunately, this doesn't work:

show.html.erb
<div>Content!</div>

show.js.erb
$("#main").fadeIn("<%= escape_javascript(render 'show') %>");

因为 Rails 将查找 show 部分,而不是实际视图.

As Rails will look for the show partial, not the actual view.

有没有办法让 Rails 查找视图文件,而不是部分文件?

Is there a way to get Rails to look for the view file, rather than a partial?

推荐答案

在另一个视图中渲染非局部视图并不是 Rails Way™.您当前的解决方案可能更好,而且不是不常见的方法.如果您对部分名称与操作相同感到奇怪,请将其重命名为 _body 或其他适当的名称.

Rendering a non-partial view inside another view isn't exactly the Rails Way™. Your current solution is probably better, and not an uncommon approach. Rename it _body, or something else appropriate, if you feel weird about the the partial name being the same as the action.

但是,如果您的视图可以共享,就像在这种情况下一样,您可以将其设为布局.

However if your view can be shared, as it seems like it could in this case, you could just make it a layout.

这是因为,有点违反最小意外原则,如果没有 js<,Rails 将为 js 操作渲染一个 html 模板 模板存在.这意味着您可以删除 js 模板和部分,然后创建一个名为 fadein.js.erb 的布局:

This is facilitated by the fact that, somewhat against the principle of least surprise, Rails will render an html template for a js action if no js template exists. This means that you could remove both the js template, and the partial, and just create a layout entitled, for example, fadein.js.erb:

# yourviews/show.html.erb
<div>Content!</div>

# layouts/fadein.js.erb
$("#main").fadeIn("<%= escape_javascript(yield) %>");

# YourController.rb
def show
  # ...
  respond_to do |wants|
    wants.html
    wants.js { render :layout => "fadein" }
  end
end

这篇关于Rails:从视图内渲染视图(不是局部)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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