如何避免在生成的URL中添加默认语言环境? [英] How to avoid adding the default Locale in generated URLs?

查看:71
本文介绍了如何避免在生成的URL中添加默认语言环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您遵循 I18N Rails指南,则所有生成的链接都包含语言环境参数(本地主机/zh/about,localhost/fr/about).这是因为我们使用方法default_url_options总是添加Locale参数:

If you follow the I18N Rails Guide, all generated links contain the locale parameter (localhost/en/about, localhost/fr/about). This is because we use the method default_url_options to always add the Locale parameter :

def default_url_options(options={})
  { :locale => I18n.locale }
end

当语言环境未知或默认语言环境时,是否可以从生成的url中删除语言环境参数?

我需要什么:

  • 区域设置未知:mysite/about
  • 语言环境en:mysite/about(而不是localhost/en/about)
  • 语言环境fr:mysite/fr/about
  • Locale unknown : mysite/about
  • Locale en : mysite/about (and not localhost/en/about)
  • Locale fr : mysite/fr/about

我尝试仅设置不是默认语言环境的语言环境,但是结果是生成的链接永远不会包含语言环境参数...

I tried to only set the locale if it was not the default one, but the result is that the generated links never contain the locale parameter...

我尝试了很多类似的事情

def default_url_options(options={})
  if I18n.locale == :fr
    { :locale => I18n.locale }
  else
    { :locale => nil }
  end
end


整个代码:

ApplicationController.rb:

before_filter :set_locale
def set_locale
  I18n.locale = params[:locale]
end

def default_url_options(options={})
  { :locale => I18n.locale }
end

routes.rb

scope "(:locale)", :locale => /en|fr/ do
  match 'about'   => 'static_pages#about',   :via => :get
  match 'contact' => 'static_pages#contact', :via => :get
  match '/' => 'search#index', :as => :search
end

root :to => 'search#index'

推荐答案

好,我理解得更好.确实,您几乎做到了.

Ok I understand much better. Indeed, you almost did it.

您只需要在Ruby中使用一个非常有用的运算符:||

You just need a very useful operator in Ruby: ||

如果第一个值存在,则使用它,否则将考虑第二个参数.

If the first value exists, it's used, otherwise the second argument is taken into account.

def set_locale
  I18n.locale = params[:locale] || :en
end

这篇关于如何避免在生成的URL中添加默认语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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