Method: ActionView::Helpers::FormBuilder#label
- Defined in:
- actionview/lib/action_view/helpers/form_helper.rb
#label(method, text = nil, options = {}, &block) ⇒ Object
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="article_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:
article:
body: "Write your entire text here"
Which then will result in
label(:body)
# => <label for="article_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:
article:
cost: "Total cost"
label(:cost)
# => <label for="article_cost">Total cost</label>
label(:title, "A short title")
# => <label for="article_title">A short title</label>
label(:title, "A short title", class: "title_label")
# => <label for="article_title" class="title_label">A short title</label>
label(:privacy, "Public Article", value: "public")
# => <label for="article_privacy_public">Public Article</label>
label(:cost) do |translation|
content_tag(:span, translation, class: "cost_label")
end
# => <label for="article_cost"><span class="cost_label">Total cost</span></label>
label(:cost) do |builder|
content_tag(:span, builder.translation, class: "cost_label")
end
# => <label for="article_cost"><span class="cost_label">Total cost</span></label>
label(:cost) do |builder|
content_tag(:span, builder.translation, class: [
"cost_label",
("error_label" if builder.object.errors.include?(:cost))
])
end
# => <label for="article_cost"><span class="cost_label error_label">Total cost</span></label>
label(:terms) do
raw('Accept <a href="/terms">Terms</a>.')
end
# => <label for="article_terms">Accept <a href="/terms">Terms</a>.</label>
2404 2405 2406 |
# File 'actionview/lib/action_view/helpers/form_helper.rb', line 2404 def label(method, text = nil, = {}, &block) @template.label(@object_name, method, text, (), &block) end |