I tried to build upon Ryan's code above and to add the possibility of setting a cookie, so that a users language selection is remembered. Here's what I came up with.
/site/templates/_init.php:
if(isset($_COOKIE["user_language"])) {
$language = $_COOKIE["user_language"];
} else {
$name = $sanitizer->pageName(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
if($name == "en") $name = "default"; // because default language cannot be renamed to en
$language = $languages->get($name);
setcookie("user_language", $language, time()+3600*24*365, "/");
}
if($language != $user->language) {
$url = substr($pages->get('/')->httpUrl, 0, -1) . $page->localUrl($language);
$session->redirect($url);
}
Then, I've added an event handler to the language select:
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURI(name) + "=" + encodeURI(value) + expires + "; path=/";
}
$(".select-language a").click(function() {
var value = $(this).attr("data-language");
createCookie("user_language", value, 365);
});
The language select itself within the template file looks like this (source):
$savedLanguage = $user->language;
foreach($languages as $language) {
if(!$page->viewable($language)) continue;
$user->language = $language;
if($language->isDefault()){$out = "en";} else {$out = $language->name;}
echo "<a href='{$page->url}' data-language='{$language->id}'>{$out}</a>";
}
$user->language = $savedLanguage;
Everything seems to work so far. But as I just began to work with processwire; does anyone of the more experienced guys see a potential problem with this solution? Ryan also mentioned possible problems with caching in his post above. Is there a way around this? Could it help if I run this code only on the startpage (instead of _init.php)?