LoginSignup
3
0

More than 3 years have passed since last update.

RailsでERBを直接使い、文字列として結果を取得する

Posted at

はじめに

Railsのviewではなく、erbの結果を文字列としてほしいケースが有ったので、その方法です。

パスにRails固有のコードを使っていますが、そこ以外はRailsじゃなくても使えます。

ERBのインスタンス生成

file = File.read(Rails.root.join('app', 'views', 'hoge', 'fuga.html.erb').to_s)
erb = ERB.new(file)

といった形でERBのインスタンスを生成できます。

Railsじゃない場合は、

file = File.read('/path/to')

みたいな感じですね。

結果の取得

result_text = erb.result_with_hash(hoge:1, fuga:2)

で結果の取得ができます。

引数に渡したハッシュが、そのままerb内でkeyを変数名、valueを値とするローカル変数として読み込まれます。

あとがき

erbを直接使いたい状況、そこまで多くはないとは思いますが、もし必要な方の役に立てば幸いです。

3
0
1

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
3
0