Laravel中如何配置多语言国际化路由

问题

假设我们有一个网站:example.com,现在我们想拥有URL被翻译过的多个国际化站点,比如example.cnexample.frexample.it等。访问example.com/hello的时候应该在站点头部标签中生成如下hreflang属性:

  • link rel="alternate" hreflang="it" href="http://example.it/ciao"
  • link rel="alternate" hreflang="it" href="http://example.cat/hola"

代码

1、在BaseController中,新增如下方法:

// app/Controller/BaseController.php

protected static function geti18nUrls()
{
    $domains = Config::get('i18n.sites');
    $translatedUrls = array();
    //Backup current locale
    $currentLocale = App::getLocale();

    foreach($domains as $domain => $locale)
    {
        $protocol = (in_array($domain,Config::get('sites.https'),true)) ? 'https://' : 'http://';

        App::setLocale($locale);
        $routeName = Route::currentRouteName();

        if( $routeName != 'index' )
        {
            $translatedUrls[$domain] = $protocol.$domain.'/'.Lang::get('routes.'.$routeName) ;
        }
        else
        {
            $translatedUrls[$domain] = $protocol.$domain;
        }
    }
    App::setLocale($currentLocale);

    return $translatedUrls;
}

2、在config目录下创建一个新的配置文件i18n.php

// Create a i18n file
// app/config/i18n.php

return array
(
    'https' => array(), //list of domains with https support.
    'sites' => array(
        'example.it',
        'example.cat',
        'example.com',
    ),
);

3、并且我们假设你已经对所有路由进行了翻译

// routes.php
switch($_SERVER['HTTP_HOST'])
{
    case 'example.com': 
        App::setLocale('en'); 
        break;
    case 'example.it': 
        App::setLocale('it'); 
        break;
    case 'example.cat': 
        App::setLocale('ca'); 
        break;
}

Route::any(Lang::get('routes.hello'),
    array('as' => 'hello', 'uses' => 'HomeController@hello'));

4、创建翻译文件resources/lang/en/routes.phpresources/lang/it/routes.phpresources/lang/ca/routes.php

//lang/en/routes.php
return array
(
    'hello' => '/hello'
);

//lang/it/routes.php
return array
(
    'hello' => '/ciao'
);

//lang/ca/routes.php
return array
(
    'hello' => '/hola'
);

使用

在所有控制器中调用该方法并渲染相应视图:

// app/controllers/ExampleController.php
class ExampleController extends BaseController
{
    public function hello()
    {
        $this->layout->with( 'hreflang', self::geti18nUrls() );
        $this->layout->content = View::make( 'hello_view' );
    }
}

编写模板文件hello_view.php

<!-- app/views/hello_view.blade -->
<head>
    <link rel="alternate" hreflang="it" href="{{ hreflang['example.it'] }}" >
    <link rel="alternate" hreflang="ca" href="{{ hreflang['example.cat'] }}" >
</head>

学院君

学院君 has written 550 articles

资深PHP工程师,Laravel学院院长