Rails: Render view from outside controller
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.
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:
- A context, representing the template search paths
- 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