15

I have a FooController that responds to HTML and JS (AJAX) queries:

# app/controllers/foo_controller.rb:
class FooController < ApplicationController
  layout 'foo'
  def bar
    respond_to do |format|
      format.html # foo/bar.html.erb
      format.js   # foo/bar.js.erb
    end
  end
end

The templates to support it:

# app/views/layouts/foo.html.erb:
<html>...<%= yield %>...</html>

# app/views/layouts/foo.json.erb:
<%= yield %>

And an AJAX template in which I want to render a partial:

# app/views/foo/bar.js.erb:
dojo.byID('some_div').innerHTML = "<%= escape_javascript(render(:partial => 'some/partial')) %>";

If the JS template just has plain old JS in it (like alert('hi');), it uses my JS template. When I put in the render(:partial), though, it makes the whole response use the HTML template, which means it's no longer valid JS.

A possible solution is to use a function for the layout:

class FooController < ApplicationController
  layout :choose_layout
  ...
  private
  def choose_layout
    return nil if request.xhr?
    'foo'
  end
end

But my version should work! Why doesn't it?

1
  • I think the reason it didn't work was a tiny bug: I had a .json.erb template, but no .js.erb one and no default .erb one. Commented Dec 8, 2008 at 16:38

2 Answers 2

8

The most recent Railscast covers this topic (using jQuery).

I'm not quite seeing where you might be going wrong, but here's a snippit from the Railscast that works just fine to render a partial:

// views/reviews/create.js.erb
$("#new_review").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
$("#reviews_count").html("<%= pluralize(@review.product.reviews.count, 'Review') %>");
$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");
$("#new_review")[0].reset();

Where are you storing your Javascript? Do you have an Application.js that you're keeping things in? If so, are you including "dojo" before "application" in your javascript_include_tag?

Sign up to request clarification or add additional context in comments.

Comments

1

Try the following;

class FooController < ApplicationController
  layout 'foo'
  def bar
    respond_to do |format|
      format.html
      format.js { render :layout => false }
    end
  end
end

Hope that helps.

J.K.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.