【问题标题】:Rails: Custom text for rails form_for labelRails:rails form_for 标签的自定义文本
【发布时间】:2012-10-11 19:15:00
【问题描述】:

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

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

这会生成标签“姓名”,但我希望它是“您的姓名”。怎么改?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3.2 form-for


    【解决方案1】:

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

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

    使用Ruby on Rails Documentation 查找辅助方法。

    【讨论】:

    • 谢谢!能否请您告诉我如何在文档中查找此类内容?
    • 只需转到上面的链接并在搜索框中输入您要查找的方法即可。 label 列在 ActionView::Helpers::FormBuilderActionView::Helpers::FormHelper 下。 ActionView::Helpers::FormBuilder是我们感兴趣的,但是没有描述。如果查看方法声明,您可以看到第二个参数是text。在这个例子中,它不是很直接。但是那个文档站点通常相当不错。
    【解决方案2】:

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

    helpers:
        label:
          user:
            name: Your Name
    

    这将允许您继续使用

    <%= f.label :name %>
    

    无需硬编码Your Name

    有关 i18n 的更多信息,请参阅this。关于label 的文档请参考this

    【讨论】:

      【解决方案3】:

      i18n 与 rails 5.2.2 完美结合。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        相关资源
        最近更新 更多