How to render HTML using a Ruby on Rails 5 API Application
Asked Answered
S

4

8

We're using Ruby on Rails 5.0.0.1 in API-Mode. What Middleware and Configurations do I need to add, in order to being able to render html instead of json in an controller.

Edit:

Thank you all for your answers.

Want I wanted is to render normal erb/haml views. not html in json like 'kartik upadhyay' mentioned. Since the Application is primary an JSON API we didn't want the full blown default Rails Installation, which mean our Application Controller extends from ActionController::API.

My Plan was to make a PdfRendering Controller which includes all Modules needed for ActionView to work. What I rather did was reading the asset pipeline (because we wanted to use sass) and inherit the application controller from ActionController::Base. as other rails apps would do.

It's not the nicest solution since you're including the whole ActionController::Base and all of it's Feature that you may not be using. But it's still slimmer that a full Blown Rails installation (especially the middleware aka. sessions etc.)

Solanum answered 12/1, 2017 at 11:47 Comment(1)
You can use templates without using the whole Rails framework. Just add slim or haml, then you can do something like Slim::Template.new(path).render(Object.new, users: users) and it renders html for you.Evalynevan
P
4
  include ActionView::Layouts
  include ActionController::Rendering

Add these to your controller

Popovich answered 25/3, 2020 at 1:14 Comment(2)
may i know what each of these modules do?Nutgall
ActionView::Layouts provides Layout and include ActionController::Rendering provides template rendering. With them, you can render *.html.erbPopovich
A
-1

You can use render to string method of rails for rendering your html as string inside json, put this inside your controller:

render json: { data: render_to_string('html_file_name') }

this will render html as response like:

{"data": "<html>\n<h3>hello</h3>\n</html>"}
Allegory answered 12/1, 2017 at 12:16 Comment(1)
This is now what he asked for.Curtsey
W
-1

you can render erb/haml/slim etc. files like the following:

format.html { render :file_name }
Wynnie answered 17/4, 2019 at 8:26 Comment(0)
A
-5

You can simply use this gem RABL.

https://github.com/nesquena/rabl

Ambulance answered 12/1, 2017 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.