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で綺麗に\nを<br>に変換する方法

Last updated at Posted at 2020-02-29

準備

まず、Stringクラスを拡張します。ファイルの置き場所はお作法です。

/lib/ext/string.rb
class String
  def to_br
    ERB::Util.h(self).gsub(/\R/, "<br>")
  end
end

先ほどのstring.rbを初期化時に読み込みます

/config/initializers/extension.rb
require 'ext/string'

これで準備完了です。

使い方

あとは任意のhtmlファイルにて、

hoge.html.erb
<%== hoge_str.to_br %>

または、

hoge.html.slim
== hoge_str.to_br

などで綺麗に<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?