107

I want to display a label in form_for:

<div class="field">
  <%= f.label :name %><br />
  <%= f.text_field :name %>
</div>

This generates the label "Name", but I want it to be "Your Name". How can I change it?

Promise Preston
  • 8,732
  • 5
  • 43
  • 70
Paul S.
  • 4,066
  • 9
  • 32
  • 51

3 Answers3

197

The second parameter to label helper will allow you to set custom text.

<%= f.label :name, 'Your Name' %>

Use Ruby on Rails Documentation to look up helper methods.

gylaz
  • 11,981
  • 6
  • 48
  • 58
  • 1
    Thank you! Could you please let me know how I can look up something like this in the documentation? – Paul S. Oct 22 '12 at 00:43
  • 4
    Just go to the above link and type in the method you are looking for in the search box. `label` is listed under `ActionView::Helpers::FormBuilder` and `ActionView::Helpers::FormHelper`. `ActionView::Helpers::FormBuilder` is the one we are interested in, but there is no description. If you look at the method declaration, you can see that second parameter is `text`. In this example, it's not very straight forward. But that documentation site is _usually_ pretty good. – gylaz Oct 22 '12 at 00:47
35

You can specify custom label text via i18n. In config/locales/en.yml, and assuming your user model is named user, you can add the following:

helpers:
    label:
      user:
        name: Your Name

This will allow you to keep using

<%= f.label :name %>

without having to hardcode Your Name.

For more information about i18n, see this. Documentation on the label refer to this.

hjing
  • 4,592
  • 1
  • 21
  • 29
0

i18n with rails 5.2.2 this works perfectly.

Translate labels, placeholders, and buttons on devise forms or other forms.

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
   <div class="mt-3">
     <label class="float-left"> <%= f.label t(:email) %> </label>
       <%= f.email_field :email, class: 'form-control', placeholder: t('.emailholder') %>
   </div>
   <div class="mt-3">
     <label class="float-left"> <%= f.label t(:password) %> </label>
       <%= f.password_field :password, class: 'form-control', placeholder: t('.passholder') %>
   </div>

   <div class="button">
     <%= f.button t('.signinbtn'), class: "" %>
   </div>
<% end %>

locals file: config/locales/en.yml

en:
  activerecord:
    ....others

  #Found in Views/devise/seasions/new <form> <*label*>
  email: "Email"
  password: "Password"

  #Views/devise <form> <placeholder & buttom>
  devise: #if your using devise forms
    #seasions/new.html.erb
    new:
      emailholder: "enter email here"
      passholder: "enter password"
      signinbtn: "SignIn"

  ....others