Jump to content

Best strategy to store the selected language in the browser with the built in language functionality


joe_g
 Share

Recommended Posts

Hi there,

I've got a client who would like to store the selected language, if it's not the default language. The only way I can think of is to use localstorage from js, but that would mean loading the whole front page, then reloading it again in the right language - ew!

Is there a better way that vibes with the built in language functionality? I'm hoping to avoid session cookies and such. Also, I'm not sure how the language redirect really works. I suppose it's done in htaccess somehow, but to capture it before it happens I wouldn't know where to 'inject' that functionality.

maybe the best solution is to not bother?

Link to comment
Share on other sites

Hello @joe_g,

I would use a $session variable for storing the user language.

$session->set("userLanguage", $user->language);

You could then perform a session redirect:

if ($session->get("userLanguage") && $user->language->name === "default") {
	$session->redirect($page->localUrl($session->get("userLanguage")));
}

I have not tested this but think it should work. ?

Regards, Andreas

Link to comment
Share on other sites

Thanks, I used your code and did this:

    if($input->get('setlang')) {
        $session->set("userLanguage", $user->language->id);
    } else {
        $langId = $session->get("userLanguage");
        if($langId) {
            $newUrl = $page->localUrl($langId);
            if ($session->get("userLanguage") && $langId !== $user->language->id) {
                $session->redirect($newUrl);
            }
        }
    
    }

..but then I realized it doesn't work together with caching... Duh. I guess it's localstorage or nothing?

Link to comment
Share on other sites

There is also an option to use cookie and htaccess

RewriteEngine On

RewriteCond %{HTTP_COOKIE} language=(ua|en) [NC]
RewriteCond %{REQUEST_URI} !^/(ua|en)/ [NC]
RewriteRule ^(.*)$ /%1/$1 [R=301,L]

 

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...