Rails: Render view from outside controller

前端 未结 8 2146
不思量自难忘°
不思量自难忘° 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:16

    "I'm trying to create an HTML string using a view." -- If you mean you're in the context of a view template, then just use a helper method or render a partial.

    If you're in some other "Plain Old Ruby Object", then keep in mind you're free to use the ERB module directly:

    erb = ERB.new("path/to/template")
    result = erb.result(binding)
    

    The trick is getting that 'binding' object that gives the context for the code in the template. ActionController and other Rails classes expose it for free, but I couldn't find a reference that explains where it comes from.

    http://www.ruby-doc.org/stdlib-2.2.0/libdoc/erb/rdoc/ERB.html#method-i-result

    0 讨论(0)
  • 2020-12-15 04:23

    For future reference, I ended up finding this handy gem that makes this a breeze:

    https://github.com/yappbox/render_anywhere

    0 讨论(0)
提交回复
热议问题