我的多词字符串在 DOM 中没有被正确解释。如何使用多字字符串确保从服务器到 HTML 的 JSON 完整性?
在 Rails 控制器中,我将 JSON 对象存储在一个变量中。当我检查服务器日志时,该对象的格式正确。然后通过 erb 将该变量传递给视图中的数据属性。但是,生成的 HTML 不正确。
# in the controller
@hash = {'subhash' => {'single' => 'word', 'double' => 'two words' } }.to_json
puts @hash.inspect
# output in the server log
=> "{\"subhash\":{\"single\":\"word\",\"double\":\"two words\"}}"
# view.html.erb
<section data-hash=<%= @hash %> ></section>
# generated html, 'double' value is incorrect
<section data-hash="{"subhash":{"single":"word","double":"two" words"}}>
# complete data value is not obtainable in the console
> $('section').data().hash
< "{"subhash":{"single":"word","double":"two"
更新
# adding html_safe does not help
{"subhash" => {"single" => "word", "double" => "two words" } }.to_json.html_safe
# results in
"{"subhash":{"single":"word","double":"two" words"}}