Rails 链接到当前页面并将参数传递给它 [英] Rails link to current page and passing parameters to it
问题描述
我通过使用 url 参数传递语言环境将 I18N 添加到我的 rails 应用程序.我的网址看起来像 http://example.com/en/users 和 http://example.com/ar/users(分别用于英语和阿拉伯语语言环境).
I am adding I18N to my rails application by passing the locale using url params. My urls are looking like http://example.com/en/users and http://example.com/ar/users (for the english and arabic locales respectively).
在我的路由文件中,我使用 :path_prefix 选项定义了我的路由:
In my routes file, I have defined my routes with a :path_prefix option:
map.resources :users, :path_prefix => '/:locale'
使用 ApplicationController 中定义的 before_filter 设置区域设置
And locale is being set using a before_filter defined in ApplicationController
def set_locale
I18n.locale = params[:locale]
end
我还定义了 ApplicationController#default_url_options,为应用程序生成的所有 url 添加区域设置:
I also defined ApplicationController#default_url_options, to add locale to all urls generated by the application:
def default_url_options(options={})
{:locale => I18n.locale}
end
我想要的是在布局标题中添加一个链接(显示在所有页面中),该链接将链接到同一页面但使用其他语言环境.
What I want is to add a link in the layout header (displayed in all pages) that would link to the same page but with the other locale.
例如,如果我正在浏览阿拉伯语语言环境,我希望在标题中添加一个英语"链接,这会将我重定向回当前页面,并将语言环境设置为英语.有没有办法在 Rails 中做到这一点?
For instance, if I am browsing the arabic locale, I want a "English" link in the header, that will redirect me back to my current page, and set the locale to english. Is there a way to do this in rails?
推荐答案
我花了一段时间才找到这个,但这是我的解决方案:
Took me a while to find this but here is my solution:
link_to 'English', url_for( :locale => 'en' )
link_to 'Deutch', url_for( :locale => 'de' )
来自此处的文档:http://api.rubyonrails.org/classes/ActionController/Base.html#M000649
生成新网址时,缺少值可以从填写当前请求的参数.为了例如, url_for :action =>‘some_action’ 将保留当前控制器,正如预期的那样.这种行为扩展到其他参数,包括:controller、:id 和任何其他放入的参数路线的路径.
When generating a new URL, missing values may be filled in from the current request‘s parameters. For example, url_for :action => ‘some_action‘ will retain the current controller, as expected. This behavior extends to other parameters, including :controller, :id, and any other parameters that are placed into a Route‘s path.
所以使用 url_for 将默认使用当前请求的参数,只需在代码中更改您想要的参数即可.在这种情况下,我只更改了 :locale,所以其他一切都保持不变.
So using url_for will default to the current request's parameters, just change the one's you want in your code. In this case all I changed was :locale, so everything else stays the same.
请注意,这也适用于隐藏":参数.所以如果你有:
Note this also works for "hidden" :parameters. So if you have:
map.my_map ':locale/my_map', :controller => 'home', :action => 'my_map'
在页面/en/my_map 中使用上面的url_for 将不会在url 中包含'home'(即/en/home/my_map).奖金.
using the above url_for in the page /en/my_map will not have 'home' in the url (ie /en/home/my_map). Bonus.
这篇关于Rails 链接到当前页面并将参数传递给它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!