Using JSON string as html attribute to form helpers
I开发者_JAVA百科 want to display a text box with some JSON in its data attribute. Here is what I do
<%= f.text_field :time, "data-options" => '{"mode": "timebox"}' %>
but it renders the following HTML
<input data-options="{"mode": "timebox"}" ...
What I want to achieve is
<input data-options='{"mode": "timebox"}' ...
I want it to enclose the attribute in single quotes without escaping the contents. Can I do it with text_field helper?
If you're sure that the JSON data will always be safe, use html_safe
or raw
:
#html_safe
<%= f.text_field :time, "data-options" => '{"mode": "timebox"}'.html_safe %>
#raw
<%= f.text_field :time, "data-options" => raw('{"mode": "timebox"}') %>
Ps. Note that I have used single quotes instead of double quotes for mode
and timebox
. (because for some reason, Rails always adds double-quotes around the attributes value when rendered in HTML).
精彩评论