【问题标题】:Rails - Current URL without locale part passedRails - 没有通过区域设置部分的当前 URL
【发布时间】:2014-02-28 12:30:29
【问题描述】:

在我的 Rails 应用程序中,我将语言环境限定为我的网址:

http://localhost:3000/de/blah/blubb
http://localhost:3000/en/blah/blubb
http://localhost:3000/es/blah/blubb
                     ^^^

如何在没有 locale 参数的情况下“获取”current_url?

http://localhost:3000/blah/blubb
                    ^^^

目前我有这个:

<%=  "#{request.protocol}#{request.host_with_port}#{request.fullpath}" %>
# http://localhost:3000/de/blah/blubb

【问题讨论】:

    标签: ruby-on-rails url locale rails-i18n


    【解决方案1】:

    您可以保留要排除的可用区域列表:

    LOCALES = %w(en de es).map { |l| l.prepend '/' }
    

    然后你可以像这样替换它们:

    <%= "#{request.protocol}#{request.host_with_port}#{request.fullpath.sub(Regexp.union(LOCALES), '')}" %>
    # /blah/blubb
    

    【讨论】:

    • 好吧,这行得通,但访问者也有可能访问http:localhost:3000/blah/blubb,您的解决方案的结果会删除我的http:localhost:3000/blubb。所以blah 不见了。你能更新你的答案吗?
    • @Jan 更新了我的答案:)
    • fullpath.s.sub? s 是从哪里来的? L 是 LOCALES 吗?
    【解决方案2】:

    如果你有这种模式

    http://localhost:3000/X/blah/blubb
    

    其中 X 可以是语言环境,但有时也可以是其他东西,那么您需要指定语言环境列表并将它们 gsub 出来:

    "#{request.protocol}#{request.host_with_port}#{request.fullpath.gsub(/^\/#{array_of_locale_strings.map{|s| "(#{s})"}.join("|")}\//,"/")}"
    

    【讨论】:

      猜你喜欢
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多