Skip to content

Instantly share code, notes, and snippets.

@electrum
Created July 15, 2011 20:31
Show Gist options
  • Select an option

  • Save electrum/1085494 to your computer and use it in GitHub Desktop.

Select an option

Save electrum/1085494 to your computer and use it in GitHub Desktop.
Passing data to JavaScript in Rails
# 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
@nealpoole

Copy link
Copy Markdown

Hmm, disregard that. The escape_javascript function apparently does more than the documentation claims :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment