Search code examples
ruby-on-railsrubyruby-on-rails-4

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!


Solution

  • In Rails 5:

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

    In Rails 6.1:

    lookup_context = ActionView::LookupContext.new(ActionController::Base.view_paths)
    context = ActionView::Base.with_empty_template_cache.new(lookup_context, {}, nil)
    
    renderer = ActionView::Renderer.new(lookup_context)
    renderer.render(context, { file: 'app/views/template.html.erb' })
    
    • ActionView::Renderer.new() takes a lookup_context arg, and render() method takes a context, so we set those up first
    • ActionView::Base is the default ActiveView context, and must be initialized with with_empty_template_cache method, else render() will error
    • The {}, nil are required assigns and controller args, which used to default to {}, nil in Rails 5
    • Rails 6.1 requires a full filepath file: 'app/views/template.html', whereas Rails 5 only required the filename