문제

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

도움이 되었습니까?

해결책

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] }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top