首页 > 解决方案 > 是否可以在 laravel 上获取已翻译字符串的键?

问题描述

我有资源/lang/fr_FR.json、resources/lang/en_US.json 等,我有西班牙语的所有键和所需语言的值。

我正在尝试翻译传入的 URL,例如,如果我使用西班牙语并选择英语,则单击“contacto”,它可以正常工作,因为我已经注册了 key contacto,但是如果我是英语,我有“联系方式”,我没有这个钥匙可以翻译。

这就是改变 url 语言环境的函数

  public function setLocale($locale, $desiredLocale)
    {
        $previousUrl = explode("/", url()->previous());
        $newUrl = array();

        foreach ($previousUrl as $segment) {
            $translatedSegment =  __($segment, [], $desiredLocale);
            array_push($newUrl, $translatedSegment);
        }
        $uri = implode("/", $newUrl);
        $uri = str_ireplace($locale, $desiredLocale, $uri);


        return redirect($uri, 301);
    }

编辑:我想要实现的目标

我在导航栏上有一个下拉菜单,其中包含 es、fr、eng 等语言,例如

我在http://localhost/laravel-project/public/es_ES/inicio,然后我点击我的下拉语言 eng 并将我发送到这条路线:

<a class="dropdown-item" href="{{route('setLocale', ['desiredLocale' => $key])}}">eng</a>

我的语言环境路线:

//Language swap
Route::get('/language/{desiredLocale}', 'LocaleController@setLocale')->name('setLocale');

我的 localeController 是我显示的函数,($locale 变量来自中间件,因此设置在 url::default 上)

它应该将我重定向到http://localhost/laravel-project/public/en_US/home

然后因为在我的 web.php 我有:

Route::get(__('inicio'), function () {
    return view('pages.home.index');
})->name('inicio');

它会在我的 en_US.json 上搜索单词和路线,它会存在:

{
    "inicio": "home",
}

标签: laravel

解决方案


推荐阅读