Rails: Render view from outside controller

前端 未结 8 2166
不思量自难忘°
不思量自难忘° 2020-12-15 03:41

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 co

8条回答
  •  执念已碎
    2020-12-15 04:15

    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
    

提交回复
热议问题