Direct #{} works for simple strings, but is not the most scalable / secure solution in general.
For example, a literal backslash in Ruby will cause problems in Javascript, where it will be interpreted as a newline:
- a = "\\n" :javascript '#{ a }' !== "\\n"
From this amazing Rails cast you can use the following methods:
escape_javascript
Alias: j .
Only works with strings.
Resets characters that may have special meanings in Javascript strings, such as escape backslashes, to a format suitable for inputting literals in Javascript.
Maintain html_safe input status, therefore html_safe is required otherwise special HTML characters such as < will be escaped to < .
- a = "\\n<" :javascript '#{ j(a) }' === '\\n<' '#{ j(a).html_safe }' === '\\n<'
to_json + html_safe
This works because JSON is almost a subset of the literal notation of Javascript objects .
It works on any hash object, including strings, arrays and integers, which are converted to JSON fragments of the corresponding data type.
- data = { key1: 'val1', key2: 'val2' } :javascript data =
data attributes
Add values to attributes, retrieve them using Javascript DOM operations.
Better with content_tag helper:
= content_tag 'div', '', id: 'data', data: {key1: 'val1', key2: 'val2'} :javascript $('#data').data('key1') === 'val1' $('#data').data('key2') === 'val2'
square
Task-specific library: https://github.com/gazay/gon
Perhaps the most reliable solution.
Gemfile:
gem 'gon'
Controller:
gon.key1 = 'val1' gon.key2 = 'val2'
Layout app/views/layouts/application.html.erb :
<html> <head> <meta charset="utf-8"/> <%= include_gon %>
View:
:javascript gon.key1 === 'val1' gon.key2 === 'val2'