How to detect language from URL in Sinatra

后端 未结 1 453
失恋的感觉
失恋的感觉 2020-12-28 11:18

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

相关标签:
1条回答
  • 2020-12-28 11:48

    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] }
    
    0 讨论(0)
提交回复
热议问题