Custom text for rails form_for label

2019-02-01 03:02发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

On Rails 5.1.0 , the accepted answer above does not work.

The first parameter passed can be used as a customized label.

"<%= f.label :mobile, "Mobile No:" %>"