Rails Render Action With Different Format
Say I have an application#search method that I would like to respond to AJAX requests开发者_如何学编程. Inside of my JS view (app/views/application/search.js.erb) I would like to render the HTML view:
$("#content").html( escape_javascript( render( :action => 'search', :format => 'html' ) ) );
$("#title").html( "Title" );
I know I could move things into a partial and render that in both the HTML and JS views, but the problem is I have many different actions that need to respond in this way and I'd prefer not creating a bunch of 1-line view files that just render a partial.
Is there any way to explicitly render an action with a specific format and grab the different parts of content_for as well? So for the above example, I could set #title to the HTML returned with content_for :title or something.
I'm not sure outputting a bunch of HTML into JS source is a great design, but that wasn't your question -- and I've had to do similar things to output HTML snippets rendered by templates into XML, which I consider more reasonable :).
Anyhow, there are several things in your question.
It changes from version to version of Rails, but in Rails 4.x, I think this should work, you were close, but it for some reason needs to be :formats
(plural) with an array. And there were some other unrelated things not right in your example, like the need for ERB <%= tags, and putting javascript strings into quote marks.
var str = "<%= escape_javascript( render( :partial => 'partial_name', :formats => ['html'] ) ) %>";
I think. I haven't tried that exactly myself.
Note that's still a partial though. You want to render a full (not partial) template from inside another template -- I'm pretty sure Rails won't let you do that. It's been a bit annoying to me before too. But in fact, even to render an HTML partial ("something.html.erb") from a JS partial, you need to use the :formats => []
trick, or Rails will insist "hey, I want to find a js partial with that name, we're in js mode man!".
But as above should render _partial_name.html.erb from a JS template. Which is still probably not a great design.
Hope this helps.
精彩评论