I need to create and then pass an array/hash from Rails into Javascript through a data tag.
The Javascript needs to be formatted like this:
[{x: 1333065600000, title: 'Title', text: 'Text'}, {x: 1333065600000, title: 'Title', text: 'Text'}]
I created a helper method in Rails to create this type of syntax:
def flags
@flags = '['
@model.flags.each do |f|
@flags += "{ x: 1333065600000, title: '#{f.title}', text: '#{f.text}'},"
end
@flags += ']'
end
The data is then passed into Javascript like so:
<%= content_tag 'div', '', id: 'container', data: {flags: flags} %>
The HTML source code looks correct, but the ‘s are encoded. Despite this, the div shows up without any errors, but also without any flags. Inputting the exact result of this directly into the Javascript shows the flags properly.
I know that the data tags are automatically JSON encoded, so I also tried using the standard HTML data tag with ERB tags nested in them, but came across the same problem.
Does anyone know what the problem might be? Any help would be greatly appreciated!
This is a cleaner way to write your helper, returning the array instead of a contrived JSON string.
I’m not sure what you’re trying to accomplish, as
is expected output. You need to decode the
data-flagsattribute before parsing it as a JSON encoded string.If for some reason you’re wanting single quotes instead of the double quotes, you can do this with
This will produce
which I assume is what you’re after.