How to detect language from URL in Sinatra

随声附和 提交于 2019-11-30 12:20:51

问题


I have a multi-language website and I'm puting the language in the URL like domain.com/en/. When the user doesn't put the language in the URL I want to redirect him to the page in the main language like "domain.com/posts" to "domain.com/en/posts". Is there an easy way to do this with Sinatra?

I have more than one hundred routes. So doing this for every route is not a very good option.

get "/:locale/posts" do... end

get "/posts" do... end

Can someone help me?

Thanks


回答1:


Use a before filter, somewhat like this:

set :locales, %w[en sv de]
set :default_locale, 'en'
set :locale_pattern, /^\/?(#{Regexp.union(settings.locals)})(\/.+)$/

helpers do
  def locale
    @locale || settings.default_locale
  end
end

before do
  @locale, request.path_info = $1, $2 if request.path_info =~ settings.locale_pattern
end

get '/example' do
  case locale
  when 'en' then 'Hello my friend!'
  when 'de' then 'Hallo mein Freund!'
  when 'sv' then 'Hallå min vän!'
  else '???'
  end
end

With the upcoming release of Sinatra, you will be able to do this:

before('/:locale/*') { @locale = params[:locale] }


来源:https://stackoverflow.com/questions/3104658/how-to-detect-language-from-url-in-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!