render to string – Rails render_to_string

render to string – Rails render_to_string

Whilst I do not think this is the best solution doing the following worked.

ac = ActionController::Base.new()  

html_string = ac.render_to_string :template => path_to_file e.g. post/show

The Application Controller file in Rails API mode inherits from ActionController::API, so I guess the functionality to render is in ActionController::Base.

You can do something like this inside your action:

     respond_to do |format|
       format.html { render layout: your_layout } # this is for your html responses if you need to respond with html
       format.json { # this block will execute for your json requests

        html = render_to_string action: :index, layout: false, :formats => [:html]
        render json: {data: html}
     }

render to string – Rails render_to_string

Try the following snippet code:

ActionController::Base.new.render_to_string(mailer/your-html-file, locals: { data: your-json-data-that-you-wanna-add-to-your-html-file })

Leave a Reply

Your email address will not be published. Required fields are marked *