【问题标题】:Simple Form I18n labels简单形式 I18n 标签
【发布时间】:2014-05-14 07:54:38
【问题描述】:

大家好,我在我的应用中构建了一个搜索框。它看起来像这样:

= simple_form_for :cars, {url: cars_path, method: :get} do |f|
  = f.input :handover_location, collection: Location.all.map{|hl| [hl.name, hl.id]}
  = f.input :return_location, collection: Location.all.map{|rl| [rl.name, rl.id]}
  = f.input :car_class, collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
  = f.submit 

现在我不知道如何用 I18n 翻译这些标签。我该怎么做?

【问题讨论】:

    标签: ruby-on-rails internationalization simple-form


    【解决方案1】:

    查看有关 i18n 的简单格式文档:https://github.com/plataformatec/simple_form#i18n

    描述得很好,而且很详细。

    例如(来自文档):

    en:
      simple_form:
        labels:
          defaults:
            username: 'User name'
            password: 'Password'
            new:
              username: 'Choose a user name'
        hints:
          defaults:
            username: 'User name to sign in.'
            password: 'No special characters, please.'
        placeholders:
          defaults:
            username: 'Your username'
            password: '****'
    

    这指定了标签的默认值。 您应该查看文档,因为还有更多选项。

    其次,你也可以明确地这样做,像这样

    = f.input :car, label: I18n.t('my_car_label'), prompt: I18n.t('my-car-prompt'), placeholder: I18n.t('my-placeholder')
    

    【讨论】:

    • 我认为这是更好的答案,因为它专注于简单的表单 gem。
    • 简单形式的文档没有被“很好地描述”,因为示例仅包含第二部分 - 字典,并且该字典没有表格示例。从您的回答中,我无法理解“simple_form_for”标签的外观,或者您没有解释问题中表格的字典应该是什么样的。
    • 虽然没那么难,文档也解释的很好,我为什么要重复呢?无论如何,简而言之,您不适应任何形式,并且在翻译中使用模型名称,然后更深入地编写属性名称,这对我来说似乎很明显。您需要更具体的示例吗?
    【解决方案2】:

    首先,我将首先阅读docs,尤其是第 3 部分。对于基于活动记录模型的表单,Rails 有一些自定义的内置支持(请参阅文档的第 4.6 部分)。例如,要将您的 Car 型号名称翻译为“汽车”以外的其他名称,您可以这样做:

    # config/locales/en.yml
    en:
      activerecord:
        models:
          car:
            one: Automobile
            other: Automobiles
    

    (替换您选择的语言以支持 I18n。)

    但是,一般来说,要使用 I18n,您需要调用 Rails 提供的 translate 方法,缩写为 t。示例:

    = simple_form_for :cars, {url: cars_path, method: :get} do |f|
      ..
      = f.label t('forms.car_class')
      = f.input :car_class, collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
      ..
      = f.submit 
    
    # config/locales/en.yml
    
    en:
      forms:
        car_class: 'Automobile'
    

    这将呈现带有文本的标签:“汽车”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多