title: How do I include HTML in a JS Rails response?
body: <p>I have a FooController that responds to HTML and JS (AJAX) queries:</p>
  
  <pre><code># app/controllers/foo_controller.rb:
  class FooController &lt; ApplicationController
    layout 'foo'
    def bar
      respond_to do |format|
        format.html # foo/bar.html.erb
        format.js   # foo/bar.js.erb
      end
    end
  end
  </code></pre>
  
  <p>The templates to support it:</p>
  
  <pre><code># app/views/layouts/foo.html.erb:
  &lt;html&gt;...&lt;%= yield %&gt;...&lt;/html&gt;
  
  # app/views/layouts/foo.json.erb:
  &lt;%= yield %&gt;
  </code></pre>
  
  <p>And an AJAX template in which I want to render a partial:</p>
  
  <pre><code># app/views/foo/bar.js.erb:
  dojo.byID('some_div').innerHTML = "&lt;%= escape_javascript(render(:partial =&gt; 'some/partial')) %&gt;";
  </code></pre>
  
  <p>If the JS template just has plain old JS in it (like <code>alert('hi');</code>), 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.</p>
  
  <p>A possible solution is to use a function for the layout:</p>
  
  <pre><code>class FooController &lt; ApplicationController
    layout :choose_layout
    ...
    private
    def choose_layout
      return nil if request.xhr?
      'foo'
    end
  end
  </code></pre>
  
  <p>But my version <em>should</em> work!  Why doesn't it?</p>