Rails:自定义form_for标签的文本

119

我想在 form_for 中显示一个标签:

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

这将生成标签 "Name",但我希望它是 "Your Name"。如何更改?

3个回答

217
< p > label助手的第二个参数可以让您设置自定义文本。

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

使用Ruby on Rails文档查找帮助方法。


1
谢谢!您能告诉我在文档中如何查找类似这样的内容吗? - Paul S.
4
只需转到上面的链接,并在搜索框中输入您要查找的方法。label列在ActionView :: Helpers :: FormBuilderActionView :: Helpers :: FormHelper下。我们感兴趣的是ActionView :: Helpers :: FormBuilder,但没有说明。如果您查看方法声明,可以看到第二个参数是text。在此示例中,它不是非常直观。但是,那个文档网站通常相当不错。 - gylaz

37
你可以通过i18n指定自定义标签文本。在config/locales/en.yml中,假设你的用户模型命名为user,你可以添加以下内容:
helpers:
    label:
      user:
        name: Your Name

这将使您能够继续使用

<%= f.label :name %>

无需硬编码Your Name

有关i18n的更多信息,请参见此处。关于label的文档,请参见此处


1

使用Rails 5.2.2进行i18n,这完美地运作。

翻译devise表单或其他表单上的标签占位符按钮

<%= 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 %>

本地文件:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接