如何即时反映URL中的语言环境变化? [英] How to reflect change of locale in URL instantly?

查看:66
本文介绍了如何即时反映URL中的语言环境变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Rails 4应用程序中有此语言环境切换器:

I have this locale switcher in my Rails 4 application:

class LocalesController < ApplicationController

  def change_locale
    if params[:set_locale]
      session[:locale] = params[:set_locale]
      redirect_to(:back, :locale => params[:set_locale])
    end
  end

end

一切正常,除了当用户切换语言环境时,新的语言环境未显示在URL中.

Everything works fine except that the new locale is not shown in the URL when the user switches the locale.

例如,当我在页面/de/faq上,然后在下拉菜单中单击English时,页面的内容将切换为英语(我想会话也将调整为英语),但是URL仍为/de/faq.只有在此之后的下一次单击,URL中的语言环境才会调整为/en/....

For example, when I'm on the page /de/faq and then click English in the drop down menu, the content of the page switches to English (and I guess the session also adjusts to English), however the URL remains /de/faq. Only the next click after that will make the locale in the URL adjust to /en/....

但是,如果可以将区域设置更改立即反映在URL中,那就太好了.

It would be nice, though, if the locale change would be reflected in the URL instantly.

这怎么办?

推荐答案

redirect_to :back不接受任何其他参数,因为它将使用请求标头提供的url.您可能应该这样做:

redirect_to :back do not accept any additional params, as it will use the url supplied by the request headers. You should probably do:

url_hash = Rails.application.routes.recognize_path URI(request.referer).path
url_hash[:locale] = params[:set_locale]
redirect_to url_hash

说明:

Rails.application.routes.recognize_path URI(request.referer).path

此行采用引荐来源网址(这是请求来自的网址,在您调用redirect_to :back时使用).然后使用URI对其进行解析,以单独提取路径,例如/de/faq.

This line takes the referer url (this is the url the request comes from and it is used when you call redirect_to :back). Then it is parsed with URI to extract the path alone, like /de/faq.

具有路径的我们正在使用Rails管道功能recognize_path.此方法使用您的路线将给定的路径转换为像{controller: 'MyController', action: 'my_action', param: 'my_param', ... }这样的哈希.由于您的路线在URL中包含语言环境,因此可以在:locale键下的此哈希中访问引荐来源URL中使用的语言环境.

Having the path we are using Rails plumbing function recognize_path. This method uses your routes to translate given path into a hash like {controller: 'MyController', action: 'my_action', param: 'my_param', ... }. Since your route includes locale in the URL, the locale used in referrer URL will be accessible in this hash under :locale key.

现在,第二行只是将此哈希中的:locale的值更改为已传递的语言环境值.然后,如果您确实使用此哈希进行重定向,则Rails将使用此哈希从中生成URL,该URL与引用URL完全相同,但语言环境除外.

Now the second line is just to change the value of :locale in this hash to whatever value of locale has been passed. Then if you do redirect with this hash, rails will use this hash to generate the URL from it, which will be exactly same as referer URL except for locale.

很可能您仍然需要使用会话来存储区域设置.

Most likely you still need to use the session to store the locale.

这篇关于如何即时反映URL中的语言环境变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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