Login Systems and More with Ruby on Rails - 15.10 Escaping HTML and JavaScript for Display
(Page 3 of 4 )
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't find the definition for the h() helper function anywhere in the Rails source code, because it's a shortcut for ERb's built-in helper function html_escape().
JavaScript is deployed within HTML tags like <SCRIPT>, 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't do much: it just turns line breaks into the string "\n", and adds backslashes before single and double quotes. This is handy when you want to use arbitrary data in your own JavaScript code:
<!-- index.rhtml -->
<script lang="javascript">
var text = "<%= escape_javascript @javascript_alert_text %>";
alert(text);
</script>
See Also
Next: 15.11 Setting and Retrieving Session Information >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.
|
|