跳至内容 跳至搜索

Action View 表单标签助手

提供了一些用于创建表单标签的方法,这些方法不依赖于分配给模板的 Active Record 对象,例如 FormHelper 所做的那样。相反,您需要手动提供名称和值。

注意:HTML 选项 disabledreadonlymultiple 都可以被视为布尔值。因此,指定 disabled: true 将给出 disabled="disabled"

方法
B
C
D
E
F
H
I
L
M
N
P
R
S
T
U
W
包含的模块

实例公共方法

button_tag(content_or_options = nil, options = nil, &block)

创建一个按钮元素,定义一个submit按钮、reset按钮或一个可用于 JavaScript 的通用按钮。例如,您可以将按钮标签用作常规提交标签,但它不受旧版浏览器的支持。但是,按钮标签允许更丰富的标签,例如图像和强调,因此此助手也将接受一个块。默认情况下,它将创建一个类型为submit的按钮标签,如果未给出类型,则如此。

选项

  • :data - 此选项可用于添加自定义数据属性。

  • :disabled - 如果为真,则用户将无法使用此输入。

  • 任何其他键都会为标签创建标准的 HTML 选项。

示例

button_tag
# => <button name="button" type="submit">Button</button>

button_tag 'Reset', type: 'reset'
# => <button name="button" type="reset">Reset</button>

button_tag 'Button', type: 'button'
# => <button name="button" type="button">Button</button>

button_tag 'Reset', type: 'reset', disabled: true
# => <button name="button" type="reset" disabled="disabled">Reset</button>

button_tag(type: 'button') do
  content_tag(:strong, 'Ask me!')
end
# => <button name="button" type="button">
#     <strong>Ask me!</strong>
#    </button>

已弃用:Rails UJS 属性

在 Rails 7 之前,Rails 默认情况下附带了一个名为 @rails/ujs 的 JavaScript 库。在 Rails 7 之后,此库不再默认启用。此库与以下选项集成

  • confirm: 'question?' - 如果存在,非侵入式 JavaScript 驱动程序将提供一个带有指定问题的提示。如果用户接受,则表单将正常处理,否则不采取任何操作。

  • :disable_with - 此参数的值将用作提交表单时提交按钮禁用版本的 value。此功能由非侵入式 JavaScript 驱动程序提供。

    button_tag “Save”, data: { confirm: “Are you sure?” } # => <button name=“button” type=“submit” data-confirm=“Are you sure?”>Save</button>

    button_tag “Checkout”, data: { disable_with: “Please wait…” } # => <button data-disable-with=“Please wait…” name=“button” type=“submit”>Checkout</button>

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 605
def button_tag(content_or_options = nil, options = nil, &block)
  if content_or_options.is_a? Hash
    options = content_or_options
  else
    options ||= {}
  end

  options = { "name" => "button", "type" => "submit" }.merge!(options.stringify_keys)

  if block_given?
    content_tag :button, options, &block
  else
    content_tag :button, content_or_options || "Button", options
  end
end

check_box_tag(name, options = {})
check_box_tag(name, value, options = {})
check_box_tag(name, value, checked, options = {})

创建一个复选框表单输入标签。

选项

  • :value - 输入的值。默认为"1"

  • :checked - 如果设置为 true,则复选框默认情况下将被选中。

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • 任何其他键都会为标签创建标准的 HTML 选项。

示例

check_box_tag 'accept'
# => <input id="accept" name="accept" type="checkbox" value="1" />

check_box_tag 'rock', 'rock music'
# => <input id="rock" name="rock" type="checkbox" value="rock music" />

check_box_tag 'receive_email', 'yes', true
# => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />

check_box_tag 'tos', 'yes', false, class: 'accept_tos'
# => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />

check_box_tag 'eula', 'accepted', false, disabled: true
# => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 455
def check_box_tag(name, *args)
  if args.length >= 4
    raise ArgumentError, "wrong number of arguments (given #{args.length + 1}, expected 1..4)"
  end
  options = args.extract_options!
  value, checked = args.empty? ? ["1", false] : [*args, false]
  html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
  html_options["checked"] = "checked" if checked
  tag :input, html_options
end

color_field_tag(name, value = nil, options = {})

创建一个类型为“color”的文本字段。

选项

支持与text_field_tag相同的选项。

示例

color_field_tag 'name'
# => <input id="name" name="name" type="color" />

color_field_tag 'color', '#DEF726'
# => <input id="color" name="color" type="color" value="#DEF726" />

color_field_tag 'color', nil, class: 'special_input'
# => <input class="special_input" id="color" name="color" type="color" />

color_field_tag 'color', '#DEF726', class: 'special_input', disabled: true
# => <input disabled="disabled" class="special_input" id="color" name="color" type="color" value="#DEF726" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 703
def color_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :color))
end

date_field_tag(name, value = nil, options = {})

创建一个类型为“date”的文本字段。

选项

支持与text_field_tag相同的选项。

示例

date_field_tag 'name'
# => <input id="name" name="name" type="date" />

date_field_tag 'date', '01/01/2014'
# => <input id="date" name="date" type="date" value="01/01/2014" />

date_field_tag 'date', nil, class: 'special_input'
# => <input class="special_input" id="date" name="date" type="date" />

date_field_tag 'date', '01/01/2014', class: 'special_input', disabled: true
# => <input disabled="disabled" class="special_input" id="date" name="date" type="date" value="01/01/2014" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 773
def date_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :date))
end

datetime_field_tag(name, value = nil, options = {})

创建一个类型为“datetime-local”的文本字段。

选项

支持与 text_field_tag 相同的选项。此外,还支持

  • :min - 最小可接受值。

  • :max - 最大可接受值。

  • :step - 可接受值的粒度。

  • :include_seconds - 在输出时间戳格式中包含秒(默认情况下为 true)。

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 801
def datetime_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: "datetime-local"))
end

datetime_local_field_tag(name, value = nil, options = {})

email_field_tag(name, value = nil, options = {})

创建一个类型为“email”的文本字段。

选项

支持与text_field_tag相同的选项。

示例

email_field_tag 'name'
# => <input id="name" name="name" type="email" />

email_field_tag 'email', 'email@example.com'
# => <input id="email" name="email" type="email" value="email@example.com" />

email_field_tag 'email', nil, class: 'special_input'
# => <input class="special_input" id="email" name="email" type="email" />

email_field_tag 'email', 'email@example.com', class: 'special_input', disabled: true
# => <input disabled="disabled" class="special_input" id="email" name="email" type="email" value="email@example.com" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 875
def email_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :email))
end

field_id(object_name, method_name, *suffixes, index: nil, namespace: nil)

为给定的名称和字段组合生成 HTML id 属性值

返回由FormBuilder为给定属性名称生成的 value。

<%= label_tag :post, :title %>
<%= text_field :post, :title, aria: { describedby: field_id(:post, :title, :error) } %>
<%= tag.span("is blank", id: field_id(:post, :title, :error) %>

在上面的示例中,<input type="text"> 元素由对 text_field 的调用构建,声明了一个 aria-describedby 属性,引用了 <span> 元素,共享一个共同的 id 根(在本例中为 post_title)。

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 102
def field_id(object_name, method_name, *suffixes, index: nil, namespace: nil)
  if object_name.respond_to?(:model_name)
    object_name = object_name.model_name.singular
  end

  sanitized_object_name = object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").delete_suffix("_")

  sanitized_method_name = method_name.to_s.delete_suffix("?")

  [
    namespace,
    sanitized_object_name.presence,
    (index unless sanitized_object_name.empty?),
    sanitized_method_name,
    *suffixes,
  ].tap(&:compact!).join("_")
end

field_name(object_name, method_name, *method_names, multiple: false, index: nil)

为给定的名称和字段组合生成 HTML name 属性值

返回由FormBuilder为给定属性名称生成的 value。

<%= text_field :post, :title, name: field_name(:post, :title, :subtitle) %>
<%# => <input type="text" name="post[title][subtitle]"> %>

<%= text_field :post, :tag, name: field_name(:post, :tag, multiple: true) %>
<%# => <input type="text" name="post[tag][]"> %>
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 132
def field_name(object_name, method_name, *method_names, multiple: false, index: nil)
  names = method_names.map! { |name| "[#{name}]" }.join

  # a little duplication to construct fewer strings
  case
  when object_name.blank?
    "#{method_name}#{names}#{multiple ? "[]" : ""}"
  when index
    "#{object_name}[#{index}][#{method_name}]#{names}#{multiple ? "[]" : ""}"
  else
    "#{object_name}[#{method_name}]#{names}#{multiple ? "[]" : ""}"
  end
end

field_set_tag(legend = nil, options = nil, &block)

创建用于对 HTML 表单元素进行分组的字段集。

legend 将成为字段集的标题(根据 W3C 可选)。options 接受与 tag 相同的值。

示例

<%= field_set_tag do %>
  <p><%= text_field_tag 'name' %></p>
<% end %>
# => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>

<%= field_set_tag 'Your details' do %>
  <p><%= text_field_tag 'name' %></p>
<% end %>
# => <fieldset><legend>Your details</legend><p><input id="name" name="name" type="text" /></p></fieldset>

<%= field_set_tag nil, class: 'format' do %>
  <p><%= text_field_tag 'name' %></p>
<% end %>
# => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset>
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 677
def field_set_tag(legend = nil, options = nil, &block)
  output = tag(:fieldset, options, true)
  output.safe_concat(content_tag("legend", legend)) unless legend.blank?
  output.concat(capture(&block)) if block_given?
  output.safe_concat("</fieldset>")
end

file_field_tag(name, options = {})

创建一个文件上传字段。如果您使用文件上传,则还需要为表单标签设置 multipart 选项

<%= form_tag '/upload', multipart: true do %>
  <label for="file">File to Upload</label> <%= file_field_tag "file" %>
  <%= submit_tag %>
<% end %>

然后,指定的 URL 将传递一个包含所选文件的 File 对象,或者如果字段为空,则传递一个 StringIO 对象。

选项

  • 为标签创建标准 HTML 属性。

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • :multiple - 如果设置为 true,*在大多数更新的浏览器中*,用户将被允许选择多个文件。

  • :accept - 如果设置为一个或多个 mime 类型,则在选择文件时,将向用户建议一个过滤器。您仍然需要设置模型验证。

示例

file_field_tag 'attachment'
# => <input id="attachment" name="attachment" type="file" />

file_field_tag 'avatar', class: 'profile_input'
# => <input class="profile_input" id="avatar" name="avatar" type="file" />

file_field_tag 'picture', disabled: true
# => <input disabled="disabled" id="picture" name="picture" type="file" />

file_field_tag 'resume', value: '~/resume.doc'
# => <input id="resume" name="resume" type="file" value="~/resume.doc" />

file_field_tag 'user_pic', accept: 'image/png,image/gif,image/jpeg'
# => <input accept="image/png,image/gif,image/jpeg" id="user_pic" name="user_pic" type="file" />

file_field_tag 'file', accept: 'text/html', class: 'upload', value: 'index.html'
# => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 347
def file_field_tag(name, options = {})
  text_field_tag(name, nil, convert_direct_upload_option_to_url(options.merge(type: :file)))
end

form_tag(url_for_options = {}, options = {}, &block)

开始一个表单标签,将操作指向使用url_for_options配置的 URL,就像 ActionController::Base#url_for 一样。表单的默认方法为 POST。

选项

  • :multipart - 如果设置为 true,则 enctype 设置为“multipart/form-data”。

  • :method - 提交表单时使用的 method,通常为“get”或“post”。如果使用“patch”、“put”、“delete”或其他动词,则会添加一个名为_method的隐藏输入来模拟通过 post 的动词。

  • :authenticity_token - 表单中使用的身份验证令牌。仅在需要传递自定义身份验证令牌字符串或完全不添加身份验证令牌字段(通过传递false)时使用。远程表单可以通过设置config.action_view.embed_authenticity_token_in_remote_forms = false来省略嵌入的身份验证令牌。这在对表单进行片段缓存时很有用。远程表单从meta标签获取身份验证令牌,因此除非支持没有 JavaScript 的浏览器,否则嵌入是不必要的。

  • :remote - 如果设置为 true,将允许 Unobtrusive JavaScript 驱动程序控制提交行为。默认情况下,此行为是 ajax 提交。

  • :enforce_utf8 - 如果设置为 false,则不会输出名为 utf8 的隐藏输入。

  • 任何其他键都会为标签创建标准 HTML 属性。

示例

form_tag('/posts')
# => <form action="/posts" method="post">

form_tag('/posts/1', method: :put)
# => <form action="/posts/1" method="post"> ... <input name="_method" type="hidden" value="put" /> ...

form_tag('/upload', multipart: true)
# => <form action="/upload" method="post" enctype="multipart/form-data">

<%= form_tag('/posts') do -%>
  <div><%= submit_tag 'Save' %></div>
<% end -%>
# => <form action="/posts" method="post"><div><input type="submit" name="commit" value="Save" /></div></form>

<%= form_tag('/posts', remote: true) %>
# => <form action="/posts" method="post" data-remote="true">

form_tag(false, method: :get)
# => <form method="get">

form_tag('http://far.away.com/form', authenticity_token: false)
# form without authenticity token

form_tag('http://far.away.com/form', authenticity_token: "cf50faa3fe97702ca1ae")
# form with custom authenticity token
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 78
def form_tag(url_for_options = {}, options = {}, &block)
  html_options = html_options_for_form(url_for_options, options)
  if block_given?
    form_tag_with_body(html_options, capture(&block))
  else
    form_tag_html(html_options)
  end
end

hidden_field_tag(name, value = nil, options = {})

创建一个隐藏的表单输入字段,用于传输由于 HTTP 的无状态性而丢失的数据,或应该对用户隐藏的数据。

选项

  • 为标签创建标准 HTML 属性。

示例

hidden_field_tag 'tags_list'
# => <input type="hidden" name="tags_list" id="tags_list" autocomplete="off" />

hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
# => <input type="hidden" name="token" id="token" value="VUBJKB23UIVI1UU1VOBVI@" autocomplete="off" />

hidden_field_tag 'collected_input', '', onchange: "alert('Input collected!')"
# => <input type="hidden" name="collected_input" id="collected_input"
     value="" onchange="alert(&#39;Input collected!&#39;)" autocomplete="off" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 308
def hidden_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :hidden, autocomplete: "off"))
end

image_submit_tag(source, options = {})

显示一个图像,单击该图像将提交表单。

source 传递给 AssetTagHelper#path_to_image

选项

  • :data - 此选项可用于添加自定义数据属性。

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • 任何其他键都会为标签创建标准的 HTML 选项。

数据属性

  • confirm: 'question?' - 这将添加一个 JavaScript confirm 提示,其中包含指定的 question。如果用户接受,则表单将正常处理,否则不执行任何操作。

示例

image_submit_tag("login.png")
# => <input src="/assets/login.png" type="image" />

image_submit_tag("purchase.png", disabled: true)
# => <input disabled="disabled" src="/assets/purchase.png" type="image" />

image_submit_tag("search.png", class: 'search_button', alt: 'Find')
# => <input class="search_button" src="/assets/search.png" type="image" />

image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button")
# => <input class="agree_disagree_button" disabled="disabled" src="/assets/agree.png" type="image" />

image_submit_tag("save.png", data: { confirm: "Are you sure?" })
# => <input src="/assets/save.png" data-confirm="Are you sure?" type="image" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 651
def image_submit_tag(source, options = {})
  options = options.stringify_keys
  src = path_to_image(source, skip_pipeline: options.delete("skip_pipeline"))
  tag :input, { "type" => "image", "src" => src }.update(options)
end

label_tag(name = nil, content_or_options = nil, options = nil, &block)

创建一个 label 元素。接受一个块。

选项

  • 为标签创建标准 HTML 属性。

示例

label_tag 'name'
# => <label for="name">Name</label>

label_tag 'name', 'Your name'
# => <label for="name">Your name</label>

label_tag 'name', nil, class: 'small_label'
# => <label for="name" class="small_label">Name</label>
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 281
def label_tag(name = nil, content_or_options = nil, options = nil, &block)
  if block_given? && content_or_options.is_a?(Hash)
    options = content_or_options = content_or_options.stringify_keys
  else
    options ||= {}
    options = options.stringify_keys
  end
  options["for"] = sanitize_to_id(name) unless name.blank? || options.has_key?("for")
  content_tag :label, content_or_options || name.to_s.humanize, options, &block
end

month_field_tag(name, value = nil, options = {})

创建一个类型为“month”的文本字段。

选项

支持与 text_field_tag 相同的选项。此外,还支持

  • :min - 最小可接受值。

  • :max - 最大可接受值。

  • :step - 可接受值的粒度。

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 816
def month_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :month))
end

number_field_tag(name, value = nil, options = {})

创建一个数字字段。

选项

支持与 text_field_tag 相同的选项。此外,还支持

  • :min - 最小可接受值。

  • :max - 最大可接受值。

  • :in - 指定:min:max 值的范围。

  • :within - 与 :in 相同。

  • :step - 可接受值的粒度。

示例

number_field_tag 'quantity'
# => <input id="quantity" name="quantity" type="number" />

number_field_tag 'quantity', '1'
# => <input id="quantity" name="quantity" type="number" value="1" />

number_field_tag 'quantity', nil, class: 'special_input'
# => <input class="special_input" id="quantity" name="quantity" type="number" />

number_field_tag 'quantity', nil, min: 1
# => <input id="quantity" name="quantity" min="1" type="number" />

number_field_tag 'quantity', nil, max: 9
# => <input id="quantity" name="quantity" max="9" type="number" />

number_field_tag 'quantity', nil, in: 1...10
# => <input id="quantity" name="quantity" min="1" max="9" type="number" />

number_field_tag 'quantity', nil, within: 1...10
# => <input id="quantity" name="quantity" min="1" max="9" type="number" />

number_field_tag 'quantity', nil, min: 1, max: 10
# => <input id="quantity" name="quantity" min="1" max="10" type="number" />

number_field_tag 'quantity', nil, min: 1, max: 10, step: 2
# => <input id="quantity" name="quantity" min="1" max="10" step="2" type="number" />

number_field_tag 'quantity', '1', class: 'special_input', disabled: true
# => <input disabled="disabled" class="special_input" id="quantity" name="quantity" type="number" value="1" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 923
def number_field_tag(name, value = nil, options = {})
  options = options.stringify_keys
  options["type"] ||= "number"
  if range = options.delete("in") || options.delete("within")
    options.update("min" => range.min, "max" => range.max)
  end
  text_field_tag(name, value, options)
end

password_field_tag(name = "password", value = nil, options = {})

创建一个密码字段,这是一个隐藏用户输入的遮罩文本字段。

选项

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • :size - 输入框中可以容纳的可见字符数。

  • :maxlength - 浏览器允许用户输入的最大字符数。

  • 任何其他键都会为标签创建标准 HTML 属性。

示例

password_field_tag 'pass'
# => <input id="pass" name="pass" type="password" />

password_field_tag 'secret', 'Your secret here'
# => <input id="secret" name="secret" type="password" value="Your secret here" />

password_field_tag 'masked', nil, class: 'masked_input_field'
# => <input class="masked_input_field" id="masked" name="masked" type="password" />

password_field_tag 'token', '', size: 15
# => <input id="token" name="token" size="15" type="password" value="" />

password_field_tag 'key', nil, maxlength: 16
# => <input id="key" maxlength="16" name="key" type="password" />

password_field_tag 'confirm_pass', nil, disabled: true
# => <input disabled="disabled" id="confirm_pass" name="confirm_pass" type="password" />

password_field_tag 'pin', '1234', maxlength: 4, size: 6, class: "pin_input"
# => <input class="pin_input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 380
def password_field_tag(name = "password", value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :password))
end

phone_field_tag(name, value = nil, options = {})

radio_button_tag(name, value, options = {})
radio_button_tag(name, value, checked, options = {})

创建一个单选按钮;使用名称相同的单选按钮组,允许用户从一组选项中进行选择。

选项

  • :checked - 如果设置为 true,则默认情况下会选中单选按钮。

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • 任何其他键都会为标签创建标准的 HTML 选项。

示例

radio_button_tag 'favorite_color', 'maroon'
# => <input id="favorite_color_maroon" name="favorite_color" type="radio" value="maroon" />

radio_button_tag 'receive_updates', 'no', true
# => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" />

radio_button_tag 'time_slot', "3:00 p.m.", false, disabled: true
# => <input disabled="disabled" id="time_slot_3:00_p.m." name="time_slot" type="radio" value="3:00 p.m." />

radio_button_tag 'color', "green", true, class: "color_input"
# => <input checked="checked" class="color_input" id="color_green" name="color" type="radio" value="green" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 491
def radio_button_tag(name, value, *args)
  if args.length >= 3
    raise ArgumentError, "wrong number of arguments (given #{args.length + 2}, expected 2..4)"
  end
  options = args.extract_options!
  checked = args.empty? ? false : args.first
  html_options = { "type" => "radio", "name" => name, "id" => "#{sanitize_to_id(name)}_#{sanitize_to_id(value)}", "value" => value }.update(options.stringify_keys)
  html_options["checked"] = "checked" if checked
  tag :input, html_options
end

range_field_tag(name, value = nil, options = {})

创建一个范围表单元素。

选项

支持与 number_field_tag 相同的选项。

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 937
def range_field_tag(name, value = nil, options = {})
  number_field_tag(name, value, options.merge(type: :range))
end

search_field_tag(name, value = nil, options = {})

创建一个类型为“search”的文本字段。

选项

支持与text_field_tag相同的选项。

示例

search_field_tag 'name'
# => <input id="name" name="name" type="search" />

search_field_tag 'search', 'Enter your search query here'
# => <input id="search" name="search" type="search" value="Enter your search query here" />

search_field_tag 'search', nil, class: 'special_input'
# => <input class="special_input" id="search" name="search" type="search" />

search_field_tag 'search', 'Enter your search query here', class: 'special_input', disabled: true
# => <input disabled="disabled" class="special_input" id="search" name="search" type="search" value="Enter your search query here" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 726
def search_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :search))
end

select_tag(name, option_tags = nil, options = {})

创建一个下拉选择框,如果设置了:multiple选项为 true,则创建一个多选选择框。

Helpers::FormOptions 可用于创建常见的 select 框,例如国家、时区或关联记录。option_tags 是一个包含 select 框选项标签的字符串。

选项

  • :multiple - 如果设置为 true,则选择将允许多选。

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • :include_blank - 如果设置为 true,则会创建一个空选项。如果设置为字符串,则该字符串将用作选项的内容,而值将为空。

  • :prompt - 创建一个提示选项,其值为空白,文本提示用户选择内容。

  • 任何其他键都会为标签创建标准 HTML 属性。

示例

select_tag "people", options_from_collection_for_select(@people, "id", "name")
# <select id="people" name="people"><option value="1">David</option></select>

select_tag "people", options_from_collection_for_select(@people, "id", "name", "1")
# <select id="people" name="people"><option value="1" selected="selected">David</option></select>

select_tag "people", raw("<option>David</option>")
# => <select id="people" name="people"><option>David</option></select>

select_tag "count", raw("<option>1</option><option>2</option><option>3</option><option>4</option>")
# => <select id="count" name="count"><option>1</option><option>2</option>
#    <option>3</option><option>4</option></select>

select_tag "colors", raw("<option>Red</option><option>Green</option><option>Blue</option>"), multiple: true
# => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
#    <option>Green</option><option>Blue</option></select>

select_tag "locations", raw("<option>Home</option><option selected='selected'>Work</option><option>Out</option>")
# => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
#    <option>Out</option></select>

select_tag "access", raw("<option>Read</option><option>Write</option>"), multiple: true, class: 'form_input', id: 'unique_id'
# => <select class="form_input" id="unique_id" multiple="multiple" name="access[]"><option>Read</option>
#    <option>Write</option></select>

select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: true
# => <select id="people" name="people"><option value="" label=" "></option><option value="1">David</option></select>

select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: "All"
# => <select id="people" name="people"><option value="">All</option><option value="1">David</option></select>

select_tag "people", options_from_collection_for_select(@people, "id", "name"), prompt: "Select something"
# => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>

select_tag "destination", raw("<option>NYC</option><option>Paris</option><option>Rome</option>"), disabled: true
# => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
#    <option>Paris</option><option>Rome</option></select>

select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard")
# => <select id="credit_card" name="credit_card"><option>VISA</option>
#    <option selected="selected">MasterCard</option></select>
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 201
def select_tag(name, option_tags = nil, options = {})
  option_tags ||= ""
  html_name = (options[:multiple] == true && !name.end_with?("[]")) ? "#{name}[]" : name

  if options.include?(:include_blank)
    include_blank = options[:include_blank]
    options = options.except(:include_blank)
    options_for_blank_options_tag = { value: "" }

    if include_blank == true
      include_blank = ""
      options_for_blank_options_tag[:label] = " "
    end

    if include_blank
      option_tags = content_tag("option", include_blank, options_for_blank_options_tag).safe_concat(option_tags)
    end
  end

  if prompt = options.delete(:prompt)
    option_tags = content_tag("option", prompt, value: "").safe_concat(option_tags)
  end

  content_tag "select", option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
end

submit_tag(value = "Save changes", options = {})

创建一个提交按钮,文本value作为标题。

选项

  • :data - 此选项可用于添加自定义数据属性。

  • :disabled - 如果为真,则用户将无法使用此输入。

  • 任何其他键都会为标签创建标准的 HTML 选项。

示例

submit_tag
# => <input name="commit" data-disable-with="Save changes" type="submit" value="Save changes" />

submit_tag "Edit this article"
# => <input name="commit" data-disable-with="Edit this article" type="submit" value="Edit this article" />

submit_tag "Save edits", disabled: true
# => <input disabled="disabled" name="commit" data-disable-with="Save edits" type="submit" value="Save edits" />

submit_tag nil, class: "form_submit"
# => <input class="form_submit" name="commit" type="submit" />

submit_tag "Edit", class: "edit_button"
# => <input class="edit_button" data-disable-with="Edit" name="commit" type="submit" value="Edit" />

已弃用:Rails UJS 属性

在 Rails 7 之前,Rails 默认情况下会附带名为 @rails/ujs 的 JavaScript 库。从 Rails 7 开始,该库不再默认启用。该库与以下选项集成

  • confirm: 'question?' - 如果存在,非侵入式 JavaScript 驱动程序将提供一个带有指定问题的提示。如果用户接受,则表单将正常处理,否则不执行任何操作。

  • :disable_with - 此参数的值将用作表单提交时禁用版本的提交按钮的值。此功能由非侵入式 JavaScript 驱动程序提供。要为单个提交标签禁用此功能,请传递 :data => { disable_with: false } 默认值为 value 属性。

    submit_tag “完成销售”,data: { disable_with: “正在提交…” } # => <input name=“commit” data-disable-with=“正在提交…” type=“submit” value=“完成销售” />

    submit_tag “保存”,data: { confirm: “您确定吗?” } # => <input name=‘commit’ type=‘submit’ value=‘保存’ data-disable-with=“保存” data-confirm=“您确定吗?” />

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 544
def submit_tag(value = "Save changes", options = {})
  options = options.deep_stringify_keys
  tag_options = { "type" => "submit", "name" => "commit", "value" => value }.update(options)
  set_default_disable_with value, tag_options
  tag :input, tag_options
end

telephone_field_tag(name, value = nil, options = {})

创建一个类型为“tel”的文本字段。

选项

支持与text_field_tag相同的选项。

示例

telephone_field_tag 'name'
# => <input id="name" name="name" type="tel" />

telephone_field_tag 'tel', '0123456789'
# => <input id="tel" name="tel" type="tel" value="0123456789" />

telephone_field_tag 'tel', nil, class: 'special_input'
# => <input class="special_input" id="tel" name="tel" type="tel" />

telephone_field_tag 'tel', '0123456789', class: 'special_input', disabled: true
# => <input disabled="disabled" class="special_input" id="tel" name="tel" type="tel" value="0123456789" />
也称为:phone_field_tag
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 749
def telephone_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :tel))
end

text_area_tag(name, content = nil, options = {})

创建一个文本输入区域;对于较长的文本输入(如博客文章或描述)使用 textarea。

选项

  • :size - 指定 textarea 尺寸(列数乘行数)的字符串(例如,“25x10”)。

  • :rows - 指定 textarea 的行数

  • :cols - 指定 textarea 的列数

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • :escape - 默认情况下,文本输入的内容将进行 HTML 转义。如果您需要未转义的内容,请将其设置为 false。

  • 任何其他键都会为标签创建标准 HTML 属性。

示例

text_area_tag 'post'
# => <textarea id="post" name="post"></textarea>

text_area_tag 'bio', @user.bio
# => <textarea id="bio" name="bio">This is my biography.</textarea>

text_area_tag 'body', nil, rows: 10, cols: 25
# => <textarea cols="25" id="body" name="body" rows="10"></textarea>

text_area_tag 'body', nil, size: "25x10"
# => <textarea name="body" id="body" cols="25" rows="10"></textarea>

text_area_tag 'description', "Description goes here.", disabled: true
# => <textarea disabled="disabled" id="description" name="description">Description goes here.</textarea>

text_area_tag 'comment', nil, class: 'comment_input'
# => <textarea class="comment_input" id="comment" name="comment"></textarea>
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 413
def text_area_tag(name, content = nil, options = {})
  options = options.stringify_keys

  if size = options.delete("size")
    options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
  end

  escape = options.delete("escape") { true }
  content = ERB::Util.html_escape(content) if escape

  content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options)
end

text_field_tag(name, value = nil, options = {})

创建一个标准的文本字段;使用这些文本字段来输入较小的文本块,例如用户名或搜索查询。

选项

  • :disabled - 如果设置为 true,则用户将无法使用此输入。

  • :size - 输入框中可以容纳的可见字符数。

  • :maxlength - 浏览器允许用户输入的最大字符数。

  • :placeholder - 字段中默认包含的文本,当字段获得焦点时会删除。如果设置为 true,则使用当前 I18n 本地化中找到的翻译(通过 helpers.placeholder.<modelname>.<attribute>)。

  • 任何其他键都会为标签创建标准 HTML 属性。

示例

text_field_tag 'name'
# => <input id="name" name="name" type="text" />

text_field_tag 'query', 'Enter your search query here'
# => <input id="query" name="query" type="text" value="Enter your search query here" />

text_field_tag 'search', nil, placeholder: 'Enter search term...'
# => <input id="search" name="search" placeholder="Enter search term..." type="text" />

text_field_tag 'request', nil, class: 'special_input'
# => <input class="special_input" id="request" name="request" type="text" />

text_field_tag 'address', '', size: 75
# => <input id="address" name="address" size="75" type="text" value="" />

text_field_tag 'zip', nil, maxlength: 5
# => <input id="zip" maxlength="5" name="zip" type="text" />

text_field_tag 'payment_amount', '$0.00', disabled: true
# => <input disabled="disabled" id="payment_amount" name="payment_amount" type="text" value="$0.00" />

text_field_tag 'ip', '0.0.0.0', maxlength: 15, size: 20, class: "ip-input"
# => <input class="ip-input" id="ip" maxlength="15" name="ip" size="20" type="text" value="0.0.0.0" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 263
def text_field_tag(name, value = nil, options = {})
  tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
end

time_field_tag(name, value = nil, options = {})

创建一个类型为“time”的文本字段。

选项

支持与 text_field_tag 相同的选项。此外,还支持

  • :min - 最小可接受值。

  • :max - 最大可接受值。

  • :step - 可接受值的粒度。

  • :include_seconds - 在输出时间戳格式中包含秒和毫秒(默认情况下为 true)。

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 787
def time_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :time))
end

url_field_tag(name, value = nil, options = {})

创建一个类型为“url”的文本字段。

选项

支持与text_field_tag相同的选项。

示例

url_field_tag 'name'
# => <input id="name" name="name" type="url" />

url_field_tag 'url', 'https://rubyonrails.net.cn'
# => <input id="url" name="url" type="url" value="https://rubyonrails.net.cn" />

url_field_tag 'url', nil, class: 'special_input'
# => <input class="special_input" id="url" name="url" type="url" />

url_field_tag 'url', 'https://rubyonrails.net.cn', class: 'special_input', disabled: true
# => <input disabled="disabled" class="special_input" id="url" name="url" type="url" value="https://rubyonrails.net.cn" />
# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 852
def url_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :url))
end

utf8_enforcer_tag()

创建隐藏的 UTF-8 强制标签。在助手类中重写此方法以自定义标签。

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 943
def utf8_enforcer_tag
  # Use raw HTML to ensure the value is written as an HTML entity; it
  # needs to be the right character regardless of which encoding the
  # browser infers.
  '<input name="utf8" type="hidden" value="&#x2713;" autocomplete="off" />'.html_safe
end

week_field_tag(name, value = nil, options = {})

创建一个类型为“week”的文本字段。

选项

支持与 text_field_tag 相同的选项。此外,还支持

  • :min - 最小可接受值。

  • :max - 最大可接受值。

  • :step - 可接受值的粒度。

# File actionview/lib/action_view/helpers/form_tag_helper.rb, line 829
def week_field_tag(name, value = nil, options = {})
  text_field_tag(name, value, options.merge(type: :week))
end