未在应用程序控制器中设置区域设置 [英] Locale not set in Application Controller

查看:88
本文介绍了未在应用程序控制器中设置区域设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经花了最后几个小时,尝试一切可能的方法来进行这项工作,进行谷歌搜索,重新设计,测试等等.

I've spent the last few hours trying everything possible to make this work, googled, redesigned, tested, etc. - but somehow doesn't get it working.

好的,我想设置I18n.locale-非常简单.

ok, I would like to set the I18n.locale - fairly simple.

基本上,我在这里实现了指南上写的内容:

Basically I implemented what is written on the guide here:

http://guides.rubyonrails.org/i18n.html

Application_controller.rb

Application_controller.rb

before_action :set_locale

def set_locale
  I18n.locale = params[:locale] || I18n.default_locale
end

实际上我的看起来像这样:

In fact mine looks like this:

class ApplicationController < ActionController::Base
   logger.info "Point A..."
   before_action :set_locale

def set_locale
  logger.info "Point B..."
  I18n.locale = extract_locale_from_accept_language_header
end

 private
    def extract_locale_from_accept_language_header
        ....

此问题是,首次访问页面时,在设置语言环境之前先设置了语言环境.如果尚未设置语言环境,我想先阅读用户的浏览器设置.使用户有机会访问其本地化站点.如果他们随后更改了语言环境(更改语言-很好,那么将设​​置语言环境,这就是他们使用的语言,直到他们决定再次切换为止).

This Problem is that the locale gets set before I can set the locale, when first accessing the page. I would like to read browser settings of user first, if no locale is yet set. To give the user a chance to get to their localized site. If they change the locale subsequently (change language - fine, then the locale is set and that's what they are using until they decide to switch again).

我在上面的代码中放置了两行,这是输出:

I placed two lines in the code above and this is the output:

Point A...
Processing by StaticPagesController#home as HTML
  Parameters: {"locale"=>"en"}
Point B...

我尝试了以下操作: -删除了application.rb中的默认语言环境:#config.i18n.default_locale =:en -禁用所有可能干扰的宝石(每次都重新启动服务器)

I tried the following: - removed default locale in application.rb: #config.i18n.default_locale = :en - disabled all gems that could possible interfere (restarted the server each time)

任何帮助将不胜感激.谢谢,G

Any help would be appreciated. Thanks, G

推荐答案

您可以尝试看看是否适合您吗?

Could you try and see if this works for you?

def set_locale 
  @locale = extract_locale_from_accept_language_header
  I18n.locale = @locale 
end

更新:

经过大量注释和粘贴的日志后,看起来好像您是通过路线获取语言环境的.这就是为什么您在日志语言环境中看到:en的原因.但是您实际想要做的是不同的,根据标题而不是url设置区域设置.从路由文件中删除语言环境引用,然后查看是否对您有用.

After a lot of comments and the logs you paste it looks like you are getting the locale via routes. This is why you see in the log locale: en . But what you actually want to do is different, set the locale based on the headers and not the url. Remove the locale references from routes files and see if that works for you.

这篇关于未在应用程序控制器中设置区域设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆