简体   繁体   English

Cakephp 4 无法更改语言环境

[英]Cakephp 4 can't change locales

I'm trying to set two buttons so depending of the language user can switch to the other.我正在尝试设置两个按钮,以便用户可以根据语言切换到另一个按钮。

In my default.php I have this, to change on click on the link AppController:在我的 default.php 中,我有这个,要更改点击链接 AppController:

              <li class="nav-item">
                <?php 
                if (I18n::getLocale() !== 'en_US'){ ?>
                  <?= $this->Html->link('EN', ['action' => 'changeLang']); ?>
                  <?php
                }else{ ?>
                  <?= $this->Html->link('ES', ['action' => 'changeLang']); ?>
                <?php } ?>
              </li>       

My AppController我的应用程序控制器

    public function changeLang():void
    {
        if (I18n::getLocale() !== 'en_US'){
            I18n::setLocale('en_US');
        }else{
            I18n::setLocale('es_ES');
        }
        $this->redirect($this->referer());

    }

My default.po (in locales/es/default.po)我的 default.po(在 locales/es/default.po 中)

#: ./src/Controller/AddressController.php:72
#: ./src/Controller/UserController.php:81
msgid "Usuario registrado."
msgstr "Registered user."

It goes in the correct lines but the code doesn't change.它在正确的行中,但代码没有改变。 What I'm doing wrong?我做错了什么?

I used var_char to see if it pass the ifs correctly and it does.我使用 var_char 来查看它是否正确地通过了 ifs,它确实通过了。

A also change the app.php in config to from A 还将配置中的 app.php 更改为

        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),

to

        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'es_ES'),

and it also works.它也有效。

If I use I18n::setLocale('es_ES');如果我使用 I18n::setLocale('es_ES'); on AppController inicialize it works, so why does it not work in my function?在 AppController 上初始化它可以工作,那么为什么它在我的 function 中不起作用?

I18n::setLocale is a per-request setting. I18n::setLocale是每个请求的设置。 You're not doing anything in the code shown to save it to a session or cookie, so it will only ever be set to the default value when starting up, or to your specified value just before redirecting (which starts a new request, which resets to the default value).你没有在显示的代码中做任何事情来将它保存到 session 或 cookie,所以它只会在启动时设置为默认值,或者在重定向之前设置为你指定的值(这会启动一个新的请求,这重置为默认值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM