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

See Also

Категории