Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails render_to_string

I am having difficulty with the rails render_to_string function. I have created an app using the --api flag, so i think this may be the issue as i have tested in 'full' rails apps and its works just fine.

Essentially i am calling:

body_html = render_to_string(template: 'reservations/print')

I have also tried

body_html = render_to_string('reservations/print')
body_html = render_to_string(partial: 'reservations/print')
body_html = render_to_string(partial: 'reservations/print.html.erb')

which should return the html for that template. The filename is print.html.erb and just has basic data i.e.

<p> Hello world. </p>

When i output the body_html it is empty.

I referenced this SO question What is the correct way to render_to_string in wicked pdf? and am also going to use Wicked PDF to generate a pdf file.

Many thanks

like image 439
Dudedolf Avatar asked Nov 08 '16 15:11

Dudedolf


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.

What are rails partials?

Ruby on Rails Views Partials Partial templates (partials) are a way of breaking the rendering process into more manageable chunks. Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates.

What is render in rails?

Rendering is the ultimate goal of your Ruby on Rails application. You render a view, usually . html. erb files, which contain a mix of HMTL & Ruby code. A view is what the user sees.

What is the layout in Ruby on Rails?

A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts. The process involves defining a layout template and then letting the controller know that it exists and to use it.


1 Answers

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.

like image 185
Dudedolf Avatar answered Oct 05 '22 23:10

Dudedolf