yii2 创建翻译后的 URL [英] yii2 create translated URLs

查看:56
本文介绍了yii2 创建翻译后的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建用户友好的 URL,这些 URL 已翻译,但指向与其他语言相同的控制器.

I need to create user-friendly URLs which are translated, yet point to the same controller as the others for a language.

示例:

/en/myCar/100 ->/de/meinAuto/100 ->/fr/monVoiture/100

/en/myCar/100 -> /de/meinAuto/100 -> /fr/monVoiture/100

我尝试使用路由,但找不到根据翻译后的 URL 调用控制器的方法.

I tried using routes but couldn't find a way to call the controller depending on a translated URL.

有什么我应该从哪里开始的提示吗?

Any hints where I should start?

推荐答案

使用内置功能无法轻松完成,但有人有同样的需求并专门为此编写了一个包:yii2-localeurls.我认为这可能是您正在寻找的内容:

It can't be done easily with built in functionality, but someone had the same need and wrote a package specifically for this: yii2-localeurls. I think that might be what you are looking for:

使用此扩展程序,您可以使用包含语言代码的 URL,例如:

With this extension you can use URLs that contain a language code like:

/en/some/page
/de/some/page
http://www.example.com/en/some/page
http://www.example.com/de/some/page

/en/some/page
/de/some/page
http://www.example.com/en/some/page
http://www.example.com/de/some/page

如果需要,您还可以配置友好名称:

You can also configure friendly names if you want:

http://www.example.com/english/some/page
http://www.example.com/deutsch/some/page

每当您创建 URL 时都会自动添加语言代码,并在解析 URL 时回读.为了获得最佳用户体验,如果 URL 中未使用语言,则会从浏览器设置中自动检测语言.不过,用户仍然可以访问其他语言,只需调用带有其他语言代码的 URL.

The language code is automatically added whenever you create a URL, and read back when a URL is parsed. For best user experience the language is autodetected from the browser settings, if no language is used in the URL. The user can still access other languages, though, simply by calling a URL with another language code.

最后请求的语言也保存在用户会话和 cookie 中.因此,如果用户尝试访问您的网站而 URL 中没有语言代码,他将被重定向到他上次访问时使用的语言.

The last requested language is also persisted in the user session and in a cookie. So if the user tries to access your site without a language code in the URL, he'll get redirected to the language he had used on his last visit.

这篇关于yii2 创建翻译后的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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