问题描述:

We are rendering json into data-attributes in ERB. Eg:

location.html.erb

<div data-location="<%= render 'location_json' %>">

location_json.erb

<%= @location.to_json(

only: [:id, :name, :lat, :lng],

method: [:display_name]) %>

The rendered html looks like:

<div data-location="{&quot;id&quot;:16,&quot;lat&quot;:&quot;35.688195&quot;,&quot;lng&quot;:&quot;-82.564652&quot;,&quot;name&quot;:&quot;Mountain&quot;}">

But I would like it to be more readable, eg:

<div data-location='{"id":16, "lat":35.688195, "lng":-82.564652, "name":"Mountain"}'>

Is there a way to tell ERB or to_json to render with single quotes instead of escaping double quotes?

Is it possible to render readable json into HTML data-attributes. By readable, I mean with the bare minimum of escaping.

网友答案:

in location.html.erb

 <div data-location="<%= @location.to_json %>">

Reference: http://api.rubyonrails.org/classes/ERB/Util.html#method-c-json_escape

网友答案:

Any gsub.(/'/, '') will escape quotes too.

You may even create a table and iterate over json's response, putting key in first td and value on the second. If you have one or two jsons will be nice. If you have a lot with delimited number of elements, create a line to each one.

网友答案:

It is not possible to use unescaped JSON in a data-attribute without breaking the html page.

However, it is possible to use escaped JSON that is more readable than the Rails/ERB default.

By default ERB escapes double quotes which makes JSON particularly hard to read. Instead

  • use single quotes for the html data attribute
  • call raw to prevent ERB from using the default escaping on your string
  • escape all the html significant chars in your string except double quotes

helper.rb

def my_html_escape(s)
  { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', "'" => '&#39;' }.each do |k,v|
   s = s.gsub(k,v)
  end
  s
end

location.html.erb

<div data-location='<%= raw my_html_escape(@location.to_json) -%>'>

produces

<div data-location='{"id":16, "lat":35.688195, "lng":-82.564652, "name":"Mountain"}'>
相关阅读:
Top