Rails: Render view from outside controller

2019-01-23 13:34发布

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!

7条回答
做个烂人
2楼-- · 2019-01-23 14:02

There is no need to over bloat your app with too many gems. As we know ERB is already included in your Rails app.

@jdf = JDF.new
@job = ERB.new(File.read(Rails.root + "app/views/entries/job.xml.erb"))
result =  @job.result(binding)

Above there is snippet of code of an app I'm working on.

  • @jdf is a object to be evaluated in the erb view.
  • In my case I needed to render xml.
  • result is a string to be saved or sent anywhere you like.
查看更多
登录 后发表回答