【问题标题】:Locale not switching in Rails 4区域设置未在 Rails 4 中切换
【发布时间】:2015-07-19 07:06:21
【问题描述】:

我的 Rails 应用程序在 rails 4.0.2 上,我在使用官方 rails guide 之后的 url 方案中的 locale 变量和 params[:locale] 切换翻译时遇到问题。我有一个单页网站my site

我的国际化路线:

scope "(:locale)", locale: /en|de/ do
  #my routes here
end

我的应用程序控制器

before_filter :set_locale
  def set_locale
     I18n.locale = params[:locale] || I18n.default_locale
     #Rails.application.routes.default_url_options[:locale]= I18n.locale
  end

  # app/controllers/application_controller.rb
  def default_url_options(options = {})
     { locale: I18n.locale }.merge options
  end

在视图中更改语言环境变量的链接:

<%= link_to_unless I18n.locale == :en, "English", locale: :en %>
|
<%= link_to_unless I18n.locale == :de, "Deutsch", locale: :de %>

发生了什么locale 变量设置正确,但翻译没有切换。如果我删除其中一个翻译文件(当前为英语和德语),语言将切换到剩余的翻译文件。当我放回另一个翻译文件并尝试通过更改语言环境变量来切换到它时,它永远不会切换到另一种语言。

为什么我的代码没有改变翻译?

【问题讨论】:

  • 我希望你能修补它,因为 Rails 4.0.2 存在一些严重的安全问题,强烈建议使用 4.0.13。像Gem Canary 这样的工具可以让您在此类问题成为麻烦之前提前发现问题。
  • 我修补了 gemset rails 4.0.13,感谢您的建议。

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


【解决方案1】:

我也有同样的问题,也许这对你来说是一个解决方案:

routes.rb

scope "(:locale)", locale: /#{I18n.available_locales.join("|")}/ do
  #your routes here
end
get '*path', to: redirect("/#{I18n.default_locale}/%{path}")
get '', to: redirect("/#{I18n.default_locale}")

application_controller.rb

def set_locale
  I18n.locale = params[:locale] if params[:locale].present?
end

def default_url_options(options = {})
  {locale: I18n.locale}
end

附言

config/locales/en.yml 中是这样的:

en:
  languages:
    en: "English"
    de: "Deutsch"

config/locales/de.yml 德语

在视图中

<%= link_to_unless_current t('languages.en'), locale: :en %>
|
<%= link_to_unless_current t('languages.de'), locale: :de %>

【讨论】:

  • 你的代码给了我一个输出缓冲区错误:syntax error, unexpected ',', expecting :: or '[' or '.' ...k_to_unless_current, "English", locale: :en );@output_buffer...
  • 好的!您需要编辑config/locales/en.yml en: languages: en: "English" de: "Deutsch" config/locales/de.yml 德语而不是视图: |
【解决方案2】:

我认为您需要更明确地定义语言环境的约束:

scope path: '(:locale)', constraints: { locale: /en|de/ } do
  # routes you want to localize
end

【讨论】:

  • 不幸的是,这并没有改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多