LoginSignup
7
6

More than 5 years have passed since last update.

Modelや素のクラスでViewのhtmlを生成したい場合は「render_anywhere」が便利

Posted at

ユースケース

DBのデータを元にHTMLを動的に生成して画面に表示したいけど、その元データとしてerbやhamlを使いたくて、更にrender 'application/tags'みたいな形で、Rails上のコードも呼び出したい!

render_anywhereを使えばいいよ

yappbox/render_anywhere

Gemfileに追加して、

gem 'render_anywhere', require: false

利用したいクラスにincludeしてあげれば使えます。以下が利用例です。

class Blog
  include RenderAnywhere

  def build_html
    render inline: self.content, type: :erb
  end
end

renderメソッドの使い方はActionView::Helpers::RenderingHelper#renderのドキュメントをご覧ください。

Gemの実装内容ですが、レンダリング用のコントローラを作成して、そのコントローラでhtmlを生成した結果を返してくる仕組みのようです(rendering_controller.rb)。若干力技な感じもあるので、ご利用は計画的に。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6