How to determine language from URL in Sinatra

I have a multilingual website and I put the language in a URL like domain.com/en/. When the user does not put the language in the URL, I want to redirect it to a page in the main language, for example, "domain.com/posts", to "domain.com/en/posts". Is there an easy way to do this with Sinatra?

I have over a hundred routes. Therefore, doing this for each route is not a good option.

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

get "/ posts" do ... end

Can someone help me?

thank

+3
source share
1 answer

before, :

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

Sinatra :

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

Source: https://habr.com/ru/post/1751451/


All Articles