繁体   English   中英

在f.label内嵌入输入(rails表单生成)

[英]Nest input inside f.label ( rails form generation )

我想使用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>

您可以使用块将表单助手嵌套在标签内。 以下是使用HAML的示例,但它也适用于ERB。

= form_for your_resource do |f|
  = f.label :first_name do
    = f.text_field :first_name

正如前面提到的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 %>

PS我还不能发布截图来展示它的样子,但是一旦我得到足够的重复点,我会。

您可以使用自定义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

然后你可以像这样使用你的表单生成器:

<% form_for(@article, :builder => SmartLabelFormBuilder) do |form| %>
  <% form.label(:title) do %>
    Title
    <%= form.text_field(:title) %>
  <% end %>
<% end %>

使用这个小解决方法

<%= f.label(:content, "#{f.check_box(:allow_posts)}\n#{:content}\n".html_safe, :class => "checkbox") %>

会给你这个

<label class="checkbox" for="pages_content"><input name="pages[allow_posts]" type="hidden" value="0"><input id="pages_allow_posts" name="pages[allow_posts]" type="checkbox" value="1">

内容

使用内置的Rails' labellabel_tag帮助程序是不可能的,因为它们不会占用块。 但是,如果你想嵌套,为什么不直接使用HTML元素? -

<label>
  <%= f.text_field :firstname %>
</label>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM