加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby on Rails:如何翻译select标签的选项?

发布时间:2020-12-17 03:17:39 所属栏目:百科 来源:网络整理
导读:我在一个编辑用户表单中创建了一个select元素: t.select :identification_type,User.identification_type_hash 哈希是 { :type_1 = 1,:type_2 = 2,... } 我需要本地化类型名称.但是我没有找到将翻译添加到locale目录中的yml文件的正确方法. 我试过了 en_US:
我在一个编辑用户表单中创建了一个select元素:

t.select :identification_type,User.identification_type_hash

哈希是

{ :type_1 => 1,:type_2 => 2,... }

我需要本地化类型名称.但是我没有找到将翻译添加到locale目录中的yml文件的正确方法.

我试过了

en_US:
  type_1: Translationg of type 1
  type_2: Translationg of type 1

  active_record:
    attributes:
      identification_type:
        type_1: Translationg of type 1
        type_2: Translationg of type 1

  identification_type:
    type_1: Translationg of type 1
    type_2: Translationg of type 1

上面没有人工作. (虽然其他东西的翻译仍然有效.)
我没有在ROR文件中找到解决方案.

那么本地化这些哈希值的正确方法是什么?

解决方法

您需要自己翻译密钥,但这很容易.假设您有以下语言环境文件:

en_US:
  identification_type:
    type_1: Translationg of type 1
    type_2: Translationg of type 1

然后您的选择标记可能如下所示:

t.select(:identification_type,User.identification_type_hash.map { |k,v| [t(k,scope: :identification_type),v] })

当然,对于视图来说这看起来很复杂,因此您可以将此代码移动到视图助手:

module ApplicationHelper
  def user_identification_type_options
    User.identification_type_hash.map do |k,v| 
      [t(k,v]
    end
  end
end

所以你的select标签看起来像这样:

t.select(:identification_type,user_identification_type_options)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读