我想通过Bootstrap创建自定义radiobuttons。 我做到了,但我想在application_helper中添加这个控件。
我目前的解决方案
<div class="btn-group" data-toggle="buttons-radio">
<% @engines2.each do |e| %>
<button type="button" class="btn <%= @car.engine_id == "#{e.id}".to_i ? 'active' : '' %>" data-toggle="button" onclick="javascript:document.getElementById('car_input_engine_id').value='<%= "#{e.id}" %>'">
<%= "#{e.name}" %>
</button>
<% end %>
<input type="hidden" id="car_input_engine_id" name="car[input_engine_id]" value="<%= @car.engine_id %>" />
</div>
<%= form_for @car, :method => "post" do |f| %>
<%= checkbox_bootstrap_tag(@engines2, @car.engine_id) %>
<%= f.submit "Test Post", :class => "btn btn-inverse" %>
<% end %>
def checkbox_bootstrap_tag(engines, car_engine_id)
content_tag :div, :class=>"btn-group", "data-toggle"=>"buttons-radio" do
engines.each do |e|
content_tag :button, :type => :button,
:class=>'btn #{car_engine_id == #{e.id}.to_i ? "active" : ""}',
"data-toggle"=>"button",
:onclick=>"javascript:document.getElementById('car_input_engine_id').value=#{e.id}" do
e.name
end
end
content_tag :input, :type => :hidden, :id=>"car_input_engine_id", :name=>"car[input_engine_id]", :value=>car_engine_id
end
end
但它不起作用。有什么想法吗?
答案 0 :(得分:1)
看看这个片段:
engines.each do |e|
...
end
它预先形成了一些东西,但结果却消失了,因为它之后还有一条线:
content_tag :input, :type => :hidden, :id=>"car_input_engine_id", :name=>"car[input_engine_id]", :value=>car_engine_id
所以你必须连接两个结果:engines.each ...
和这一行的结果。
而且我认为您正在计划engines.map
代替engines.each
:获取button
- 数组的数组。
然后你必须修改这一行:
:class=>'btn #{car_engine_id == #{e.id}.to_i ? "active" : ""}',
您正在尝试执行插值(#{..}
),但是您将其包装在单引号'..'
中。您可以使用%[ ... ]
(其中[
是首选项问题,如果您需要,可以使用%{...}
或其他括号),如果您的字符串包含混合的单/双引号。
content_tag
input
也不合适。 input
标记必须包含哪些内容?对,完全没有内容!所以请改用简单的tag
助手。
所以,这就是我得到的:
def checkbox_bootstrap_tag(engines, car_engine_id)
content_tag :div, :class=>"btn-group", "data-toggle"=>"buttons-radio" do
engines_html = engines.map do |e|
content_tag :button,
:type => :button,
:class=> %[btn #{car_engine_id == e.id ? "active" : ""}],
:data => {:toggle => "button"},
:onclick=> "javascript:document.getElementById('car_input_engine_id').value=#{e.id}" do
e.name
end
end
safe_join(engines_html) +
tag(:input, :type => :hidden, :id=>"car_input_engine_id", :name=>"car[input_engine_id]", :value=>car_engine_id)
end
end
请注意safe_join
的用法:此助手对于将数组元素与HTML标记合并非常有用(在输出之前不要将它们转义)。
此外,:data => {:toggle => "button"},
部分必须告诉您Rails帮助程序知道此属性。