search
LoginSignup
59
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Railsでのhtmlのsanitize & escape

概要

  • xssなどの対策のためhtmlをescapeしたり、sanitizeするかと思います
  • viewで行う分にはhelper使って行えばいいんですが、、、

方法

  • viewでescape
    • <%=~ %>を使えば勝手にescape(rails3以降)
  • 逆にviewでescapeしない
escapeしない
<p>
<%= "html".html_safe %>
</p>
# or
<p>
<%= raw "html" %>
</p>
  • viewでsanitize
sanitize
<p>
<%= sanitize "html" %>
</p>
  • controllerからhelperを呼ぶ方法
controllerからhelperを呼ぶ
ApplicationController.helpers.hogehoge();
# or
view_context.hogehoge();
  • controllerでescape
escape
ERB::Util.html_escape("html");
  • controllerでescapeしない
escapeしない
ApplicationController.helpers.raw("html");
# or
view_context.raw("html");
  • controllerでsanitizeする
sanitize
ApplicationController.helpers.sanitize("html");
# or
view_context.sanitize("html");

参考

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
59
Help us understand the problem. What are the problem?