LoginSignup
71
54

More than 5 years have passed since last update.

simple_formatの使い方

Last updated at Posted at 2018-02-26

simple_format

概要

simple_format - リファレンス - - Railsドキュメント

  • 文字列を <p> で括る
  • 改行は <br /> を付与
  • 連続した改行は、 </p><p> を付与

使用例

使用しない場合

#simple_formatを使用しない
<% text = "テキスト\nテキスト\n\nテキストテキスト" %>
<%= text %>
出力結果
テキスト
テキスト

テキストテキスト

実際表示結果
スクリーンショット 2018-02-26 0.24.39.png

使用した場合

#simple_formatを使用する
<% text = "テキスト\nテキスト\n\nテキストテキスト" %>
<%= simple_format text %>
出力結果
<p>テキスト
<br />テキスト</p>

<p>テキストテキスト</p>

表示結果
スクリーンショット 2018-02-26 0.27.03.png

概要にある通りpタグで括られ、改行は <br /> に変換さえ
連続した改行は </p><p> が付与されている

タグが埋め込まれている場合

注意しないといけないのがタグが埋め込まれている場合はエスケープされなくなってしまう。

使用しない場合

<% text = "<h1>テキスト\nテキスト\n\nテキストテキスト</h1>" %>
<%= text %>
出力結果
&lt;h1&gt;テキスト
テキスト

テキストテキスト&lt;/h1&gt;

表示結果
スクリーンショット 2018-02-26 0.38.30.png

使用した場合

<% text = "<h1>テキスト\nテキスト\n\nテキストテキスト</h1>" %>
<%= simple_format text %>
出力結果
<p><h1>テキスト
<br />テキスト</p>

<p>テキストテキスト</h1></p>

表示結果
スクリーンショット 2018-02-26 0.41.51.png

エスケープされない原因

simple_formatソースを見てみる

#simple_format
def simple_format(text, html_options = {}, options = {})
  wrapper_tag = options.fetch(:wrapper_tag, :p)

  text = sanitize(text) if options.fetch(:sanitize, true)
  paragraphs = split_paragraphs(text)

  if paragraphs.empty?
    content_tag(wrapper_tag, nil, html_options)
  else
    paragraphs.map! { |paragraph|
      content_tag(wrapper_tag, raw(paragraph), html_options)
    }.join("\n\n").html_safe
  end
end

上記にある通り最後に #html_safe で処理されているためエスケープされなくなっている。

#sanitizeについて

最初にある sanitize で除去されそうだがデフォルトでは以下のタグは許可されている。

>> ActionView::Base.sanitized_allowed_tags
=> #<Set: {"strong", "em", "b", "i", "p", "code", "pre", "tt", "samp", "kbd", "var", "sub", "sup", "dfn", "cite", "big", "small", "address", "hr", "br", "div", "span", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "dl", "dt", "dd", "abbr", "acronym", "a", "img", "blockquote", "del", "ins"}>

なので上記以外の <strike> タグを指定してみると。

text
=> "<strike>テキスト\nテキスト\n\nテキストテキスト</strike>"

sanitize text
=> "テキスト\nテキスト\n\nテキストテキスト"

と除去されます。

エスケープする対応方法

#h を使用する

エスケープして#simple_formatを使用する
<% text = "<h1>テキスト\nテキスト\n\nテキストテキスト</h1>" %>
<%= simple_format h text %>
出力結果
<p>&lt;h1&gt;テキスト
<br />テキスト</p>

<p>テキストテキスト&lt;/h1&gt;</p>

表示結果
スクリーンショット 2018-02-26 23.09.05.png

71
54
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
71
54