Rails: Rails form_for label 的自定义文本

我想在 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?

81276 次浏览

label助手的第二个参数将允许您设置自定义文本。

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

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

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

helpers:
label:
user:
name: Your Name

This will allow you to keep using

<%= f.label :name %>

而不必硬编码 Your Name

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

I18n 和 Rails5.2.2这个工作非常完美。

设计表格或其他表格上翻译 标签placeholders纽扣

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