如何修复:i18n 始终转换为默认语言环境

How to fix: i18n always translate to default locale

我正在尝试使用 i18n 对 Rails 应用程序进行国际化。我用两种语言做了一些小测试:英语和法语。

我遇到的问题是 i18n 总是转换为默认语言环境。所以如果是英文,一切都是英文的,法语也一样。

这是我尝试过的:

config/initializers/locales.rb

# Permitted locales available for the application
I18n.available_locales = [:en, :fr]

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

    def default_url_options
        { locale: I18n.locale }
    end

end

config/application.rb

module LanguageApp
  class Application < Rails::Application
    ...
    config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/*.{rb,yml}"]
    config.i18n.default_locale = :en
    # I change the default locale here to :fr or :en
  end
end

config/routes.rb

root to: "home#index"

get '/:locale/about' => 'about#index'
get '/:locale' => 'home#index'

我这样组织我的 yml 文件:

config/locales/views/about/en.yml

en:
  about: "This page is about us."

config/locales/views/about/fr.yml

fr:
  about: "Cette page est à propos de nous."

config/locales/views/home/en.yml

en:
  welcome: "Hello world"

config/locales/views/home/fr.yml

fr:
  welcome: "Bonjour le monde"

最后是我的观点:

app/views/about/index.html.erb

About us page. <%= t(:about) %>

app/views/home/index.html.erb

This is the homepage. <%= t(:welcome) %>

我认为问题可能出在我组织 yml 文件的方式上,但我不明白为什么 i18n 只翻译为默认语言环境而 'ignore' 其他语言。

编辑:

为了在浏览器中使用 rails 服务器 运行 进行尝试,我尝试访问这些 URL:

localhost:3000
localhost:3000/en
localhost:3000/fr

这 3 个 URL 给我相同的内容,所以 :fr 语言环境实际上不起作用(它 returns 与 :en 的翻译相同)

也一样
localhost:3000/en/about
localhost:3000/fr/about

我也在rails控制台试过了:

> I18n.t(:welcome, :en)
"Hello world"
> I18n.t(:welcome, :fr)
"Hello world"

首先为请求设置语言环境:

class ApplicationController < ActionController::Base
    around_action :switch_locale
 
    def switch_locale(&action)
        I18n.with_locale(params[:locale] || I18n.default_locale, &action)
    end

    def default_url_options
        { locale: I18n.locale }
    end
end

不要像许多旧答案/教程那样使用 I18n.locale=

I18n.locale can leak into subsequent requests served by the same thread/process if it is not consistently set in every controller. For example executing I18n.locale = :es in one POST requests will have effects for all later requests to controllers that don't set the locale, but only in that particular thread/process. For that reason, instead of I18n.locale = you can use I18n.with_locale which does not have this leak issue.

如果您想为特定视图创建翻译,您应该嵌套键而不是仅仅使用平面哈希:

en:
  home:
    welcome: "Hello World"

fr:
  home:
    welcome: "Bonjour le monde"

然后在视图中使用隐式查找:

<h1><%= t('.welcome') %></h1>

这会将密钥解析为 home.welcome