Havoc quote when sending data to html attribute

I want to publish some data as an html attribute. Suppose there is a rail variable

@fields = [{:name => "id", :type => :integer}] 

I want to publish on a page for use with jquery.data (). So in .html.erb I have

 <%= form_tag( {:action => 'whatever'}, {... , :"data-fields" => h(@fields.to_json)}) %> 

But when rendering the quotes on the line [{"name":"id","type":"integer"}] other attributes were messed up because Rails form_tag uses double quotes to wrap the entire json string in double quotes. How to send json with strings as an attribute from Rails?

+4
source share
5 answers

Have you tried the following?

 <%= form_tag { :action => "whatever" }, { :data => { :fields => h(@fields.to_json) } } %> 
0
source

Here's how I stepped over the problem:

In the form tag, I did :"data-fields" => @fields.to_json.gsub('"',"'") .

This creates HTML of this kind:

 "data-fields"="[{'name':'id','type':'integer'}]" 

And then, in JS, I get it like this:

 $.parseJSON($('form').data('fields').replace(/'/g,'"')) 
0
source

Have you tried escape_javascript ? Although it has known flaws , this is not really for JSON acceleration, and I'm not sure if quotes will work in HTML attributes.

0
source

There is an episode on railscasts that deals with your situation using a serializer. The fact is that the serializer replaces double quotes with $ quot; The serial analyzer also gives you the ability to choose which attributes to serialize and include associations.

0
source

After some trial and error, this is what works.

Server side:

 <% @fields = [{:name => "id", :type => :integer}] %> <%= form_tag( '/posts/new', {id:'example',:data => { :fields=>@fields}}) %> 

Generated HTML:

 <form accept-charset="UTF-8" action="/posts/new" data-fields="[{&quot;name&quot;:&quot;id&quot;,&quot;type&quot;:&quot;integer&quot;}]" id="example" method="post"> 

Javascript wiht jQuery data method

 fields = $('#example').attr('data-fields') 

I am using rails 2.3.8 and jquery-rails 2.2.1

0
source

All Articles