Created
July 15, 2011 20:31
-
-
Save electrum/1085494 to your computer and use it in GitHub Desktop.
Passing data to JavaScript in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Returns escaped +text+ for use in a JavaScript script tag. | |
| # The string is marked html_safe to prevent characters such as | |
| # '&' and '<' from being converted to HTML entities, which must | |
| # not happen as script tag content is defined to be CDATA. | |
| # | |
| # Example: | |
| # <script>alert('<%= html_safe_js('hello & bye') %>')</script> | |
| # | |
| # Do not use this function for JavaScript used in an attribute value | |
| # such as 'onclick'. In that case, use +escape_javascript+ instead: | |
| # <p onclick="alert('<%= escape_javascript('hello & bye') %>')"> | |
| # | |
| # For reference: | |
| # http://www.w3.org/TR/html4/appendix/notes.html#notes-specifying-data | |
| def html_safe_js(text) | |
| escape_javascript(text).html_safe | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm, disregard that. The escape_javascript function apparently does more than the documentation claims :)