Rails链接到当前页面并向其传递参数 [英] Rails link to current page and passing parameters to it

查看:78
本文介绍了Rails链接到当前页面并向其传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用url参数传递语言环境来将I18N添加到我的rails应用程序中.我的网址看起来像 http://example.com/en/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.

例如,如果我正在浏览阿拉伯语区域设置,则我希望标题中有一个英语"链接,该链接会将我重定向回当前页面,并将语言环境设置为英语.有办法做到这一点吗?

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不会在网址中添加"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屋!

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