0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails ヒアドキュメントの改行を反映させる方法

Posted at

はじめに

Rails での改行を反映させる方法について、フォームやテキストエリアでの記事は見かけますが、ヒアドキュメントでの記事はあまり見かけないので、簡単に書いてみました。
やり方としては他と変わりません。

実行までの大まかな流れ

  1. userインスタンスの生成
  2. user.introduce を実行し、ヒアドキュメントを@msgに代入
  3. 受け取ったデータをビューで表示
# controller
class HomesController << ApplicationController
  def index
    user = User.new
    @msg = user.introduce
  end

# model
class User
  def introduce

  end

  def introduce
    <<~EOS

    テキスト
    テキスト
    テキスト
    
    EOS
  end
# views
<%= @msg %>
# 実行結果
 #=> テキストテキストテキスト

実はこれだとヒアドキュメントの改行は反映されません。
どうすれば改行まで反映されるのか。

simple_format メソッド

出力したいものに simple_format を使うだけです。
これでヒアドキュメントの改行が反映されます。

# views
<%= simple_format(@msg) %>
# 実行結果
  #=>  テキスト
  #    テキスト
  #    テキスト

結果

simple_format を使うと\n などの改行を <br /> タグに変換してくれる。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?