Using a JSON string as an html attribute to create helpers

I want to display a text box with some JSON in its data attribute. That's what I'm doing

<%= f.text_field :time, "data-options" => '{"mode": "timebox"}' %>

but it displays the following HTML

<input data-options="{&quot;mode&quot;: &quot;timebox&quot;}" ...

I want to reach

<input data-options='{"mode": "timebox"}' ...

I want it to include the attribute in single quotes, without leaving the content. Can I do this with the text_field helper?

+3
source share
1 answer

If you are sure that the JSON data will always be safe, use html_safeor 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 used single quotes instead of double quotes for modeand timebox. (because for some reason Rails always adds double quotes around the attribute value when rendering in HTML).

+1

All Articles