如何从 Sinatra 中的 URL 检测语言 [英] How to detect language from URL in Sinatra

查看:14
本文介绍了如何从 Sinatra 中的 URL 检测语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多语言网站,我将语言放在 URL 中,例如 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.

获取/:locale/posts"做...结束

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

获取/posts"做...结束

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 检测语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆