【问题标题】:Rails I18n redirect default languageRails I18n 重定向默认语言
【发布时间】:2014-10-20 20:44:26
【问题描述】:

我有一个使用 Rails I18n API 创建的多语言 Rails 网站,其 URL 类似于

“example.com/en/about”或“example.com/de/about”或“example.com/en/contact”

等等

这可以正常工作,但我希望如果用户访问“example.com/about”(URL 中没有语言部分),他将被重定向到默认语言的相应页面,例如到“example.com/en/about”

我的 config/routes.rb 看起来像:

Example::Application.routes.draw do
  get '/:locale' => 'static_pages#home'
  scope "/:locale" do
    root "static_pages#home"
    match 'about', to: 'static_pages#about', via: 'get'
    match 'contact', to: 'contact#new', via: 'get'
  end
  resources "contact", only: [:new, :create]
end

我可以在服务器 (apache) 级别重定向 URL,但我更喜欢在 rails 中执行此操作。

【问题讨论】:

    标签: ruby-on-rails routes url-redirection rails-i18n


    【解决方案1】:

    你可以做这样的事情 在你的路线中

    Rails.application.routes.draw do
      scope "(:locale)", locale: /en|es/ do
    
    
      root                'static_pages#home'
      get 'static_pages' => 'static_pages#home'
      get '/:locale' => 'static_pages#home'
      get    'help'    => 'static_pages#help'
      get    'about'   => 'static_pages#about'
      get    'contact' => 'static_pages#contact'
      get    'signup'  => 'users#new'
      get    'login'   => 'sessions#new'
      post   'login'   => 'sessions#create'
      delete 'logout'  => 'sessions#destroy'
      end
    

    在你的 ApplicationController 中

        before_action :set_locale
    
      def set_locale
        if params[:locale] && I18n.available_locales.include?(params[:locale].to_sym)
          cookies['locale'] = { :value => params[:locale], :expires => 1.year.from_now }
          I18n.locale = params[:locale].to_sym
        elsif cookies['locale'] && I18n.available_locales.include?(cookies['locale'].to_sym)
          I18n.locale = cookies['locale'].to_sym
        end
      end
    
      protect_from_forgery
    
        def default_url_options(options={})
        logger.debug "default_url_options is passed options: #{options.inspect}\n"
        { :locale => I18n.locale }
         end
    
      def extract_locale_from_tld
        parsed_locale = request.host.split('.').last
        I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 2019-12-31
      • 2014-11-27
      • 1970-01-01
      相关资源
      最近更新 更多