PHP code example of dlds / yii2-localeurls

1. Go to this page and download the library: Download dlds/yii2-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/ */

    

dlds / yii2-localeurls example snippets



return [
    // ...

    'bootstrap' => ['localeUrls'],

    // ...

    'components' => [
        // ...

        'localeUrls' => [
            'class' => 'dlds\localeurls\LocaleUrls',

            // List all supported languages here
            'languages' => ['en_us', 'en', 'fr', 'de']
        ]

        // Override the urlManager component
        'urlManager' => [
            'class' => 'dlds\localeurls\UrlManager',
        ]

        // ...
    ]
];

 $url = Url:to(['demo/action']) 

<?= $url = Url:to(['demo/action', 'language'=>'fr']) 

<?= Url:to(['demo/action', 'language'=>'de']) 

<?= Url:to(['demo/action', 'language'=>'fr']) 


use Yii;
use yii\bootstrap\Dropdown;

class LanguageDropdown extends Dropdown
{
    private static $_labels;

    public function init()
    {
        $route = '/'.Yii::$app->controller->route;
        $appLanguage = Yii::$app->language;
        $params = $_GET;

        array_unshift($params, $route);

        foreach (Yii::$app->localeUrls->languages as $language) {
            if ($language===$appLanguage) {
                continue;   // Exclude the current language
            }
            $params['language'] = $language;
            $this->items[] = [
                'label' => self::label($language),
                'url' => $params,
            ];
        }
        parent::init();
    }

    public static function label($code)
    {
        if (self::$_labels===null) {
            self::$_labels = [
                'de' => Yii::t('language', 'German'),
                'fr' => Yii::t('language', 'French'),
                'en' => Yii::t('language', 'English'),
            ];
        }

        return isset(self::$_labels[$code]) ? self::$_labels[$code] : null;
    }
}