【问题标题】:Route groups for localization in Laravel 5.1Laravel 5.1 中本地化的路由组
【发布时间】:2023-03-31 14:10:01
【问题描述】:

我的网站上有三种语言:

en, fr, de

我希望网站上的所有页面都在第一段的 url 中使用语言,即。

/page     ->set Locale as English
/de/page  ->set Locale as German
/fr/page  ->set Locale as French

知道如何将其应用于所有路线吗?必须根据第一个 URL 段设置语言,如果不是“de”或“fr”,则将语言设置为英语。谢谢!

【问题讨论】:

  • 有一套英语路线和一套其他路线可以吗?当前缀不存在时,我无法使用路由组可选前缀使其工作。否则你唯一的选择就是把语言放在最后。
  • 是的,它可能,但让我问你一些事情,如何将路线组限制为只有“fr”和“de”Route::group(['prefix' => '{lang}'], function () { })->where('lang', '[fr|de]');这个代码是虚构的......Route::group()不能附加@ 987654325@给它
  • 我可能会使用中间件来处理。

标签: laravel laravel-5 laravel-routing


【解决方案1】:

我现在可以使用 foreach 循环了。

<?php

// routes.php

Route::group(['middleware' => 'lang'], function () {

    $langPrefixes = array_merge(config('app.langs'), ['']);

    foreach ($langPrefixes as $lang)
    {
        Route::get($lang . '/', [
            'uses' => 'PropertyController@index'
        ]);

        Route::get($lang . '/stuff', [
            'uses' => 'PropertyController@stuff'
        ]);
    }

});

在 config/app.php 中:

<?php

// config/app.php

'langs' => ['fr', 'de'], // new addition

和中间件:

<?php

// Middleware/SetLanguage.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Application;

class SetLanguage
{
    protected $app;

    /**
     * Get access to the IoC container
     *
     * @param  Illuminate\Foundation\Application  $auth
     * @return void
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (in_array($request->segment(1), $this->app['config']['app.langs']) )
        {
            // override 'en' as the app locale
            $this->app['config']['app.locale'] = $request->segment(1);
        }

        return $next($request);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2016-02-11
    • 2016-04-13
    • 1970-01-01
    相关资源
    最近更新 更多