【问题标题】:How to integrate the language in the URL in Sinatra如何在 Sinatra 的 URL 中集成语言
【发布时间】:2015-11-12 09:27:12
【问题描述】:

我有一个包含多种语言的应用程序,现在我想在 URL 中集成语言。像这样的东西:https://example.com/en/main/carshttps://example.com/fr/main/cars 等等。该应用程序适用于每种语言,只是 URL 中缺少该语言。

我已经检查了thisthis,但我没有成功。我将不胜感激。

helpers.rb 我有:

def set_locale( new_locale )
  allowed_locales = %w[ de en fr it sk ]
  if allowed_locales.map{|l| l.to_sym }.include?( new_locale.to_sym )
    session[:locale] = new_locale.to_sym
  else
    session[:locale] = default_locale
  end
end
alias_method :set_lang, :set_locale

def locale
  session[:locale] || default_locale
end

def default_locale
  :de
end

def t( *args )
  I18n.locale = locale
  I18n.t( *args )
end

def l( *args )
  I18n.locale = locale
  I18n.l( *args )
end

app.rb 我定义如下:

Class Something < Sinatra::Application
  helpers Sinatra::Something::Helpers
  I18n.load_path += Dir[File.join(settings.root, 'locales', '??.yml').to_s]

  before "/*" do
    set_locale params[:locale] if params[:locale]
    set_locale params[:lang]   if params[:lang]
    set_locale params[:l]      if params[:l]
  end
end

【问题讨论】:

    标签: ruby url internationalization sinatra rails-i18n


    【解决方案1】:

    鉴于您显示的代码,您无法将 url 的第一部分设置为语言参数。尝试从您链接的文档中添加前置过滤器:

    before '/:locale/*' do
        I18n.locale       =       params[:locale]
        request.path_info = '/' + params[:splat ][0]
    end
    

    或者,您可以编辑路线以包含并命名此参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 2020-04-23
      • 2017-03-18
      • 2016-11-29
      • 1970-01-01
      相关资源
      最近更新 更多