开发者

Using JSON string as html attribute to form helpers

开发者 https://www.devze.com 2023-03-12 14:57 出处:网络
I开发者_JAVA百科 want to display a text box with some JSON in its data attribute. Here is what I do

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="{&quot;mode&quot;: &quot;timebox&quot;}" ...

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消