PHP code example of yii2-extensions / localeurls

1. Go to this page and download the library: Download yii2-extensions/localeurls library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yii2-extensions / localeurls example snippets




declare(strict_types=1);

use yii2\extensions\localeurls\UrlLanguageManager;

return [
    'components' => [
        'urlManager' => [
            'class' => UrlLanguageManager::class,
            'languages' => ['en', 'es', 'fr', 'de'],
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                '' => 'site/index',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ],
        ],
    ],
];



declare(strict_types=1);

use yii\helpers\Url;

// URL are automatically localized based on the current language

// /en/ (if current language is 'en')
Url::to(['site/index']);
// /es/site/about (if current language is 'es')
Url::to(['site/about']);
// Force specific language
Url::to(['site/contact', 'language' => 'fr']); // /fr/site/contact



declare(strict_types=1);

use yii\helpers\{Html, Url};

// Create language switcher links
foreach (Yii::$app->urlManager->languages as $language) {
    echo Html::a(
        strtoupper($language),
        Url::current(['language' => $language]),
    );
}



declare(strict_types=1);

// Get current language
$currentLang = Yii::$app->language;
// Get default language
$defaultLang = Yii::$app->urlManager->getDefaultLanguage();