instance method label

Ruby on Rails 5.2.8.1

Since v3.0.20

Available in: v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

label(method, text = nil, options = {}, &block)

Returns a label tag tailored for labelling an input field for a specified attribute (identified by method) on an object assigned to the template (identified by object). The text of label will default to the attribute name unless a translation is found in the current I18n locale (through helpers.label.<modelname>.<attribute>) or you specify it explicitly. Additional options on the label tag can be passed as a hash with options. These options will be tagged onto the HTML as an HTML element attribute as in the example shown, except for the :value option, which is designed to target labels for radio_button tags (where the value is used in the ID of the input tag).

Examples

label(:title)
# => <label for="post_title">Title</label>

You can localize your labels based on model and attribute names. For example you can define the following in your locale (e.g. en.yml)

helpers:
  label:
    post:
      body: "Write your entire text here"

Which then will result in

label(:body)
# => <label for="post_body">Write your entire text here</label>

Localization can also be based purely on the translation of the attribute-name (if you are using ActiveRecord):

activerecord:
  attributes:
    post:
      cost: "Total cost"

label(:cost)
# => <label for="post_cost">Total cost</label>

label(:title, "A short title")
# => <label for="post_title">A short title</label>

label(:title, "A short title", class: "title_label")
# => <label for="post_title" class="title_label">A short title</label>

label(:privacy, "Public Post", value: "public")
# => <label for="post_privacy_public">Public Post</label>

label(:terms) do
  raw('Accept <a href="/terms">Terms</a>.')
end
# => <label for="post_terms">Accept <a href="/terms">Terms</a>.</label>

Parameters

method req
text opt = nil
options opt = {}
block block
Source
# File actionview/lib/action_view/helpers/form_helper.rb, line 2025
      def label(method, text = nil, options = {}, &block)
        @template.label(@object_name, method, text, objectify_options(options), &block)
      end

Defined in actionview/lib/action_view/helpers/form_helper.rb line 2025 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::FormBuilder

Type at least 2 characters to search.

↑↓ navigate · open · esc close