Render a View in Rails 5 API

Render a view in Rails 5 API

You don't need to uncomment config.api_only = true for this purpose, just inherit your controller from ActionController::Base, or do it in your ApplicationController (default for common rails generation).

Code:

  1. For this controller only YourController < ActionController::Base
  2. For all apllication ApplicationController < ActionController::Base

How to render file in Rails 5 API?

If I change the parent class to ActionController::Base everything works as expected. But I don't want to inherit the bloat of full class, I need slim API version.

Yes, if you serve index from ApplicationController, changing its base class would affect all other controllers. This is not good. But what if you had a specialized controller to serve this page?

class StaticPagesController < ActionController::Base
def index
render file: 'public/index.html'
end
end

This way, you have only one "bloated" controller and the others remain slim and fast.

Rails 5 API - How to respond with HTML on a specific controllers as an exception?

According to the Layouts and Rendering Guide:

When using html: option, HTML entities will be escaped if the string is not marked as HTML safe by using html_safe method.

So you just need to tell it the string is safe to render as html:

# modified this line, though could be done in the actual render call as well
html = "<html><head></head><body><h1>Holololo</h1></body></html>".html_safe

respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end


Related Topics



Leave a reply



Submit