从视图调用 en.yml 常量

Calling en.yml constants from views

Rails 5.2
SimpleForm

我正在查看 sample-form_bootstrap 的源代码,以了解有关 Rails 的更多信息。

在 en.yml 文件中,我看到:

  simple_form:
    labels:
      user:
        email: Email
        first_kiss: First kiss
    hints:
      user:
        name: Text input example
        email: We'll never share your email with anyone else.
        password: Password input example
        color: Collection as inline radio buttons example
        fruit: Collection as inline check boxes example
    options:
      user:
        color:
          red: Red
          pink: Pink
          violet: Violet
          indigo: Indigo
          blue: Blue
          teal: Teal
          green: Green
          yellow: Yellow
        fruit:
          apple: Apple
          banana: Banana
          cherry: Cherry
          coconut: Coconut
          grape: Grape
          lime: Lime
          mango: Mango
          orange: Orange
          pear: Pear
          pineapple: Pineapple

如果我这样做:

User::COLOR

我得到:

 [:red, :pink, :violet, :indigo, :blue, :teal, :green, :yellow]

但是,如果我尝试这样的事情:

SimpleForm::LABELS

我得到一个未初始化的常量错误SimpleForm::LABELS

根据我的观点,如何从 en.ym 调用常量,尤其是集合,有什么规则?

假设您有这个 en.yml 结构:

en: simple_form: options: user: role: admin: 'Administrator' editor: 'Editor'

对于集合,您可以使用此 f.input :role, collection: [:admin, :editor]SimpleForm#I18n

上的完整指南

此外,您可以直接解析YML

require 'yaml'
thing = YAML.load_file('en.yml') # Assuming your en.yml file here.
puts thing["simple_form"]["labels"]

我查看了 SimpleForm 文档实际上 User::COLORuser 模型中的常量,而不是从 en.

加载它

您收到 未初始化常量错误 SimpleForm::LABELS 因为没有定义常量。

如果你想将它们定义为常量并在你的视图中使用它们,你可以这样做:

app_config.rb中首先像这样读取en.yml文件

info = Rails.root.to_s + '/config/locales/en.yml'
data = YAML.load_file(info).deep_symbolize_keys!

然后定义一个常量,如下所示,

LABELS = data[:simple_form][:labels]

这样您就可以在整个应用程序中使用 LABELS 常量。