Rails: Render view from outside controller

前端 未结 8 2179
不思量自难忘°
不思量自难忘° 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条回答
  •  猫巷女王i
    2020-12-15 04:00

    Rails 5 now supports 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).

    The test shows a handful of additional options and approaches.

提交回复
热议问题