【问题标题】:Laravel - How to make a button that set my locale during a whole session until the session ends or other button to change the locale?Laravel - 如何制作一个在整个会话期间设置我的语言环境的按钮,直到会话结束或其他按钮来更改语言环境?
【发布时间】:2018-05-15 02:09:02
【问题描述】:

我已经有 php 文件,其中包含 pt-br 和 es 的 tradutions。现在我必须创建 2 个按钮来将语言环境切换为 es 和 pt。我正在使用 php/laravel。

【问题讨论】:

标签: php laravel button locale


【解决方案1】:

使用这些行设置语言环境。

Route::get('switch/{locale}', function ($locale) { 
    App::setLocale($locale); 
});

【讨论】:

  • 当我使用它时。出现错误sayng Undefined class App。
  • 使用 \App::setLocale($locale);
  • 这样,用户将被重定向到 site.com/switch/pt 并出现找不到页面。我可以做些什么让用户留在他的当前页面上?
  • 执行return redirect()->back();返回上一页。
  • 它不起作用,我的猜测是:当返回一些路由或函数如 back() 时,配置回退 => 'en' 被激活。
【解决方案2】:

如果您想通过 url 设置语言环境,您可能需要在 RouteServiceProvider.php 中添加这些行。

public function boot()
{
    I18n::bootI18nService();

    parent::boot();
}

I18n::bootI18nService() 中,做类似的事情

    $language = Request::segment(1);
    App::setLocale($language);

在你的 routes/web.php 的开头,添加

Route::prefix(App::getLocale())->group(function (){

  // your routes
})

然后,如果您访问 yoursite.com/en/blabla,您的网站将显示英文翻译。

这只是一个粗略的解决方法,实际代码应该更加健壮。

【讨论】:

猜你喜欢
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多