joe_g Posted May 10, 2022 Posted May 10, 2022 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?
AndZyk Posted May 10, 2022 Posted May 10, 2022 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
joe_g Posted May 12, 2022 Author Posted May 12, 2022 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?
Zeka Posted May 12, 2022 Posted May 12, 2022 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] 3
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now