1

I have a controller method that returns JSON. But sometimes part of that JSON object should include a rendered, serialized HTML view. So my controller method has a line like this:

html = render_to_string :partial => 'foo/bar'
# ...
render json: {x: 'y', html: html}

But that fails because Rails is only looking for JSON views!

ActionView::MissingTemplate (Missing partial foo/bar with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee, :slim, :haml]}. […]

How can I solve this?


Update: I have gotten one "level" of layout to render_to_string as html using the below syntax, but the same error persists when that layout renders its own partials!

html = render_to_string :partial => "foo/bar.html.haml"

Surely there’s a solution here, right?


Update 2: render_to_string :action => 'method_in_this_controller' seems to be doing the trick.

4
  • try: html = render_to_string :partial => 'foo/bar', :formats=>[:html] Commented Oct 19, 2012 at 7:56
  • Thanks for the suggestion! I may be doing it wrong, but that doesn't seem to do the trick. Commented Oct 19, 2012 at 8:11
  • Would it be good to make 2 request? one for the html if needed, and after that the json? Single purpose is always good. May take a few more lines of code and an extra ajax call. But who knows. Just my 2cents. Commented Oct 19, 2012 at 17:51
  • A good suggestion, Phu Phan; but since this will be used in a mobile app, it makes sense to avoid needless extra HTTP requests. I don’t understand why this is so difficult; surely it’s a common-enough use case, right? Commented Oct 19, 2012 at 19:08

3 Answers 3

2

Repeating Yanhao's answer because I ran into this exact problem and its what worked for me.

try:

html = render_to_string :partial => 'foo/bar', :formats=>[:html]
Sign up to request clarification or add additional context in comments.

Comments

0

I am writing something like that in my action:

def show
  ...
  respond_to do |format|
    format.js { render :json => data }
  end
end

May be it will help you.

1 Comment

Where are you rendering a template to HTML within your method?
0

Are you sure you have a file 'apps/views/foo/_bar.*'? I was able to render HTML as a JSON parameter with How do I render a partial to a string?

respond_to do |format|
   format.html { redirect_to post_path(post) }
   format.js { 
     render json: { 
       error: flash[:error],
       content: (render_to_string partial: '/comments/comment', locals: {comment: comment}, layout: false )  
     } 
   }
end

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.