Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Render view from outside controller

I'm trying to create an HTML string using a view. I would like to render this from a class that is not a controller. How can I use the rails rendering engine outside a controller? Similar to how ActionMailer does?

Thanks!

like image 633
prajo Avatar asked Feb 04 '15 22:02

prajo


People also ask

How can you tell Rails to render without a layout?

2.2. By default, if you use the :plain 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 and use the . text. erb extension for the layout file.

What is Local_assigns?

local_assigns is a Rails view helper method that you can check whether this partial has been provided with local variables or not. Here you render a partial with some values, the headline and person will become accessible with predefined value.

How do you use nested layouts Rails?

The normal Rails app views are presented in a higher-level layout that has a little less markup surrounding it. Nesting layouts is actually quite easy. It uses the content_for method to declare content for a particular named block, and then render the layout that you wish to use.

What is render partial Rails?

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.


2 Answers

Rails 5 and 6 support this in a much more convenient manner that handles creating a request and whatnot behind the scenes:

rendered_string = ApplicationController.render(   template: 'users/show',   assigns: { user: @user } ) 

This renders app/views/users/show.html.erb and sets the @user instance variable so you don't need to make any changes to your template. It automatically uses the layout specified in ApplicationController (application.html.erb by default). Full documentation can be found here.

The test shows a handful of additional options and approaches.

like image 148
coreyward Avatar answered Sep 28 '22 12:09

coreyward


You can use ActionView::Base to achieve this.

view = ActionView::Base.new(ActionController::Base.view_paths, {}) view.render(file: 'template.html.erb') 

The ActionView::Base initialize takes:

  1. A context, representing the template search paths
  2. An assigns hash, providing the variables for the template

If you would like to include helpers, you can use class_eval to include them:

view.class_eval do   include ApplicationHelper   # any other custom helpers can be included here end 
like image 39
cweston Avatar answered Sep 28 '22 13:09

cweston