问题描述
我有一个多语言网站,并将该语言放在domain.com/en/之类的URL中.当用户未在网址中输入语言时,我想将其重定向到主要语言(例如"domain.com/posts")的页面到"domain.com/en/posts".使用Sinatra可以轻松做到这一点吗?
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 "/posts" do... end
有人可以帮助我吗?
谢谢
推荐答案
使用前置过滤器,如下所示:
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
在即将发布的Sinatra版本中,您将可以执行以下操作:
With the upcoming release of Sinatra, you will be able to do this:
before('/:locale/*') { @locale = params[:locale] }
这篇关于如何从Sinatra中的URL检测语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!