【问题标题】:Is it possible to have hyphens in a yaml key for use in my I18n en.yml file?在我的 I18n en.yml 文件中是否可以在 yaml 密钥中使用连字符?
【发布时间】:2015-07-23 09:17:06
【问题描述】:

例如:

en:
  foobar-does-not-work: 'This is my value'

如果我这样做:

t(foobar-does-not-work) # => returns nil

这不会在 Ruby 的 yml 中解析。有什么方法可以让它工作吗?我的密钥基于其中包含破折号 (-) 的 URL。

【问题讨论】:

  • 我认为在键中使用破折号是允许的,并且不应该产生问题。你确定是破折号吗?
  • @zwippie 我很肯定。 Ruby 不允许这样做。
  • 好吧,我试过了,我的 Ruby(版本)确实允许。你使用的是哪个 Ruby 版本?
  • @zwippie 我很抱歉!它似乎确实适用于原始红宝石。我想我的情况是在解析我的 en.yml ( Il8n 文件)时它不起作用。更新了我的问题
  • 字符串周围没有引号。这只是一个错字(因为你说它返回 nil 而不是语法错误)?

标签: ruby-on-rails ruby yaml rails-i18n


【解决方案1】:

很明显,有一个潜在的问题需要找出来。有一个非常好的工具可以将你的 i18n YAML 分析为 Rails 应用程序,我发现它对调试非常有帮助。

安装并运行这个 gem i18n-tasks: https://github.com/glebm/i18n-tasks

要为您的 i18n 组件创建一份综合报告:

$ i18n-tasks health

根据他们的规范:

This gem analyses code statically for key usages, such as I18n.t('some.key'), in order to:

Report keys that are missing or unused.
Pre-fill missing keys, optionally from Google Translate.
Remove unused keys.
Thus addressing the two main problems of i18n gem design:

Missing keys only blow up at runtime.
Keys no longer in use may accumulate and introduce overhead, without you knowing it.

我不确定 gem 是否打算用作 i18n 调试工具,但我发现它对于调试 i18n 中难以发现的问题很有用。

【讨论】:

    【解决方案2】:

    我认为您在调用t 方法时只是使用了错误的键。从键中删除“en”。应该是:

    t('foobar-does-not-work')
    

    【讨论】:

    • 超级好点。我刚刚检查了我的代码,我意识到我只在示例中包含了它。即使删除了 en 似乎仍然无法正常工作
    【解决方案3】:

    您使用的是哪个版本的 ruby​​?你能告诉我们你的代码和错误吗?

    它对我有用:

    > require 'yaml'
    > YAML.load_file('foo.yml')
    {"en"=>{"foobar-does-not-work"=>"This is my value"}} 
    

    当我将它添加到我的 en.yml 时它可以工作:

    > I18n.t('foobar-does-not-work')
    => "This is my value" 
    

    你检查过 I18n.locale 的值吗?

    【讨论】:

    • 嗯,很有趣。是的,它似乎确实像您的示例一样在控制台中工作。但是由于某种原因,当我通过 en.yml ( Il8n 文件)执行此操作时,它不会加载。更新了我的问题
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多