Ad

OctoberCMS - Rainlab Translate

- 1 answer

I am looking for a way to set the default locale for certain host servers.

Given the servername is server-spain, e.g. I would like to redirect by default to the spanish translation, preferably any page the user lands, besides browser settings. So by default, even the app language/locale is English by default, if accessing through website.es (spanish domain) the user will see spanish as default language.

$this['servername'] = gethostname(); // host name
{% if servername is same as('server-in-spain') %}
// reload with spanish locale
{% endif %}

Anybody found themselves in this situation? Anybody solved it?

Thanks!

Ad

Answer

You can add this code to your layout's code section and it should do the job.

use RainLab\Translate\Classes\Translator;

public function onStart() {
    
    $translator = Translator::instance();
    $currentLocale = $translator->getLocale();
    $newLocale = 'es';
    $translatedRedirect = false;
    $servername = gethostname(); // <- YOUR FUNCTION TO FIND HOST
    
    // MAKE SURE IF YOU DO NOT HAVE GIVEN LOCAE IN Backend
    // THNE IT WILL REDIRECT TO DEFAULT SET LOCALE
    if($servername === 'server-in-spain') {
        $newLocale = 'es';        
                
    }
    if($servername === 'server-in-germany') {
        $newLocale = 'de';    
    }
    
    // we do not want to redirect if user have already perfect locale
    if($currentLocale !== $newLocale) {
        $translatedRedirect = true;
    }
    
    if($translatedRedirect) {
        
        $translator->setLocale($newLocale);
        $currentUrl = $this->currentPageUrl();
        
        $parts = parse_url($currentUrl);
        $path = array_get($parts, 'path');
        
        $pageUrl = http_build_url($parts, [
            'path' => '/' . $translator->getPathInLocale($path, $newLocale)
        ]);

        return Redirect::to($pageUrl);
    }    
}

enter image description here

It should do the job

if any doubt please comment

Ad
source: stackoverflow.com
Ad