11

如何在 ruby​​ on rails 上自动设置语言环境?例如,如果网页是在西班牙打开的,那么 locale=es,同样,如果它是在英国,那么 locale=en 等等?

请帮帮我。

4

5 回答 5

27

你可以在你的ApplicationController

class ApplicationController < ActionController::Base
  before_filter :set_locale

  def set_locale
    I18n.locale = extract_locale_from_headers
  end

  private

  def extract_locale_from_headers
    request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first.presence || 'en'
  end
end

它将“检查”收到的请求,找到客户端浏览器的语言并将其设置为您的 I18n 语言环境。

查看有关 I18n 的RubyOnRails 指南以获取更多说明。


我强烈建议拥有一组受支持的语言环境并回退到默认语言环境。像这样的东西:

ALLOWED_LOCALES = %w( fr en es ).freeze
DEFAULT_LOCALE = 'en'.freeze

def extract_locale_from_headers
  browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
  if ALLOWED_LOCALES.include?(browser_locale)
    browser_locale
  else
    DEFAULT_LOCALE
  end
end
于 2012-11-09T15:27:22.960 回答
9

尝试使用gem geocoderi18n_data gem并有一个 before_filter 到一个方法

def checklocale
  I18n.locale =  I18nData.country_code(request.location.country) 
end
于 2012-11-09T15:40:15.390 回答
4

包括这是ApplicationControllerBaseController

before_filter :set_locale

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

这意味着设置locale为默认值或使用请求中的区域设置,优先于请求中发送的区域。如果您想将此扩展到用户、会话、请求,您可以这样做。

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

更多信息在这里类似的问题。

于 2012-11-09T15:32:15.193 回答
1

If i get what u mean, u will have to work with geolocation, get the user location based on his ip, and then set the locale based on it, but u must not forgot to set some default in case u can't get nothing of the user's ip.

Im sorry to say, but i didnt worked with geolocation on ruby yet. I did a fast research on rubygems and couldnt find any gem to simplify your work. =(

于 2012-11-09T15:32:57.487 回答
0

Rails Guide中,将此代码包含在 ApplicationController 中

before_action :set_locale

def set_locale
  I18n.locale = extract_locale_from_tld || I18n.default_locale
end

# Get locale from top-level domain or return nil if such locale is not available
# You have to put something like:
#   127.0.0.1 application.com
#   127.0.0.1 application.it
#   127.0.0.1 application.pl
# in your /etc/hosts file to try this out locally
def extract_locale_from_tld
  parsed_locale = request.host.split('.').last
  I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end

本质上,这会从诸如 application.co.id 或 example.com 之类的 url 中去除最终标识符(.en、.id 等),并基于此设置语言环境。如果用户来自您不支持的语言环境,它将返回到默认语言环境 - 英语,除非另有设置。

于 2015-09-24T10:34:02.850 回答