LoginSignup
7
0

More than 3 years have passed since last update.

Railsのhtmlエスケープ方法比較

Posted at

Ruby on Railsでユーザが入力したテキストを改行コードを含めて、そのまま表示したい場合があります。或いは、htmlのタグを完全に外したり、一部有効なまま残したりしたい場合もあります。

そうした場合のアプローチ比較のつもりで検証したのですが、ほとんどの場合、そのまま(何もしない)か、sanitizeを使えば良いのではないかと思います。


<% text = "<b>1</b>\n<i>2</i>\n3 >= a" %>
<%= text %> <%# そのまま(タグはエスケープされる) %>
<hr/>
<%= h(text) %> <%# そのままと一緒(使う意味ない?) %>
<hr/>
<%= simple_format(text) %> <%# 勝手に改行 & pタグが付く(お好みで..) %>
<hr/>
<%= strip_tags(text) %> <%# タグが消える %>
<hr/>
<%= sanitize(text) %> <%# 危ないタグだけ消える %>
<hr/>
<%= sanitize(text.gsub("\n","<br>")) %> <%# br(改行)は残る! %>
7
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
7
0