Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return HTML directly from a Rails controller?

One of my model objects has a 'text' column that contains the full HTML of a web page.

I'd like to write a controller action that simply returns this HTML directly from the controller rather than passing it through the .erb templates like the rest of the actions on the controller.

My first thought was to pull this action into a new controller and make a custom .erb template with an empty layout, and just <%= modelObject.htmlContent %> in the template - but I wondered if there were a better way to do this in Rails.

like image 339
Nate Avatar asked Dec 24 '09 15:12

Nate


People also ask

How can you tell Rails to render without a layout *?

By default, if you use the :text option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option.

How do I render in Ruby on Rails?

From the controller's point of view, there are three ways to create an HTTP response: Call render to create a full response to send back to the browser. Call redirect_to to send an HTTP redirect status code to the browser. Call head to create a response consisting solely of HTTP headers to send back to the browser.

How do you render partials?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .


3 Answers

In your controller respond_to block, you can use:

render :text => @model_object.html_content

or:

render :inline => "<%= @model_object.html_content %>"

So, something like:

def show
  @model_object = ModelObject.find(params[:id])

  respond_to do |format|
    format.html { render :text => @model_object.html_content }
  end
end
like image 131
Dan McNevin Avatar answered Oct 02 '22 17:10

Dan McNevin


In latest Rails (4.1.x), at least, this is much simpler than the accepted answer:

def show
  render html: '<div>html goes here</div>'.html_safe
end
like image 24
Vincent Woo Avatar answered Oct 02 '22 19:10

Vincent Woo


Its works for me

def show
  @model_object = ModelObject.find(params[:id])

   respond_to do |format|
    format.html { render :inline => "<%== @model_object['html'] %>" }
  end
end
like image 43
Selvamani Avatar answered Oct 02 '22 17:10

Selvamani