【问题标题】:Rails3: Prefix to all url_for URLSRails3:所有 url_for URLS 的前缀
【发布时间】:2011-03-22 15:40:42
【问题描述】:

我将 i18n 添加到我的网页(不同语言的不同内容)。我的网址看起来像这样:

http://host.tld/de/news/15
http://host.tld/en/news/15
...

我在应用程序中的所有 URL 都是由 link_to/url_for 这样的方法设置的

url_for("/news/#{news.id}/#{urlify(news.title)}")
url_for("/news/#{@news.section}")
...

我的路由如下所示:

scope "/:language/", :language => /de|en/ do
  match "news/:news_id(/:title)" => "news#show_entry", :constraints => { :news_id => /[0-9]+/ }
  ...
end

我将它添加到我的 ApplicationController:

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

现在我想在不更改所有 url_for() 调用的情况下将语言前缀添加到所有 URL。有没有解决方案(参数/配置选项或其他东西)来添加这个前缀?它也应该适用于相对路径。

【问题讨论】:

    标签: ruby-on-rails-3 scope url-routing


    【解决方案1】:

    如果您不想更改调用的所有 url,您可以在 application_helper.rb 文件中添加一个方法来覆盖现有方法以添加到语言中

    def url_for(options={})
      if options[:language]
        '/options[:language]' + super
      else
        super
      end
    end
    
    def link_tolink_to(*args, &block)
      options = args[1] || {}
      if options[:language]
        '/options[:language]' + super
      else
        super
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多