Escaping HTML and JavaScript for Display
Problem
You want to display data that might contain HTML or JavaScript without making browsers render it as HTML or interpret the JavaScript. This is especially important when displaying data entered by users.
Solution
Pass a string of data into the h() helper function to escape its HTML entities. That is, instead of this:
<%= @data %>
Write this:
<%=h @data %>
The h() helper function converts the following characters into their HTML entity equivalents: ampersand (&), double quote ("), left angle bracket (<), and right angle bracket (>).
Discussion
You won find the definition for the h() helper function anywhere in the Rails source code, because its a shortcut for ERbs built-in helper function html_escape().
JavaScript is deployed within HTML tags like , so escaping an HTML string will neutralize any JavaScript in the HTML. However, sometimes you need to escape just the JavaScript in a string. Rails adds a helper function called escape_javascript() that you can use. This function doesn do much: it just turns line breaks into the string " ", and adds backslashes before single and double quotes. This is handy when you want to use arbitrary data in your own JavaScript code:
See Also
- Chapter 11
Категории