Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

Rails: Render a View (not a partial) From Within a View

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') %>");

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') %>");

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

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

question from:https://stackoverflow.com/questions/16328472/rails-render-a-view-not-a-partial-from-within-a-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...