Mic*_*ael 18 html forms label ruby-on-rails
我想使用f.label方法来创建表单元素标签,但是 - 我希望将表单元素嵌套在标签内.这可能吗?
- 来自W3C -
要隐式地将标签与另一个控件相关联,控制元素必须位于LABEL元素的内容中.在这种情况下,LABEL可能只包含一个控制元素.标签本身可以位于相关控件之前或之后.
在此示例中,我们隐式地将两个标签与两个文本输入控件相关联:
<form action="..." method="post">
<p>
<label>
First Name
<input type="text" name="firstname" />
</label>
<label>
<input type="text" name="lastname" />
Last Name
</label>
</p>
</form>
Run Code Online (Sandbox Code Playgroud)
Dan*_*and 23
您可以使用块将表单助手嵌套在标签内.以下是使用HAML的示例,但它也适用于ERB.
= form_for your_resource do |f|
= f.label :first_name do
= f.text_field :first_name
Run Code Online (Sandbox Code Playgroud)
正如前面提到的Dan Garland,您可以使用简单的块将输入嵌套在标签内.我提供这个答案作为一个使用ERB的例子,特别是为了准确地说明如何使Bootstrap按钮组像单选按钮一样工作,因为它们需要这种嵌套.我花了一段时间才弄明白,所以希望这会帮助别人.
对于此示例(Rails 4.2),按钮组允许用户在3个不同的距离选项之间进行选择:
<%= form_for(@location) do |f| %>
<div class="field form-group">
<%= f.label :distance %><br>
<div class="btn-group" data-toggle="buttons">
<%= f.label :distance, class: "btn btn-primary active" do %>
<%= f.radio_button :distance, 0.3, checked: true %>
0.3 miles
<% end %>
<%= f.label :distance, class: "btn btn-primary" do %>
<%= f.radio_button :distance, 0.5 %>
0.5 miles
<% end %>
<%= f.label :distance, class: "btn btn-primary" do %>
<%= f.radio_button :distance, 1 %>
1 mile
<% end %>
</div>
</div>
<div class="actions">
<%= f.submit "Submit Location", class: "btn btn-success" %>
</div>
<% end %>
Run Code Online (Sandbox Code Playgroud)
PS我还不能发布截图来展示它的样子,但是一旦我得到足够的重复点,我会.
小智 8
您可以使用自定义FormBuilder来允许标签助手接受块.这很简单:
class SmartLabelFormBuilder < ActionView::Helpers::FormBuilder
def label(method, content_or_options_with_block = nil, options = {}, &block)
if !block_given?
super(method, content_or_options_with_block, options)
else
options = content_or_options_with_block.is_a?(Hash) ? content_or_options_with_block.stringify_keys : {}
@template.content_tag(:label, options, &block)
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用你的表单生成器:
<% form_for(@article, :builder => SmartLabelFormBuilder) do |form| %>
<% form.label(:title) do %>
Title
<%= form.text_field(:title) %>
<% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)