Developer Forum
How to change path when select a language
11 months ago by Mohammad Aazim
I am using nextjs and I wanna change the path of the url when I select a language. For example my base url or my english url is www.xyz.com, when I select a language like french or spanish, the path should change to www.xyz.com/fr or www.xyz.com/es."
How to achieve this?
11 months ago by Kirk BobashAdmin
Hi Mohammad,
I know that I already answered this question in your support ticket, but I'm posting here in case anyone else needs this solution in the future.
The following sample code can be used to change the URL when a new language is selected. Be sure to change the languages in the AVAILABLE_LANGUAGES and SOURCE_LANGUAGE constants.
/* Set up a listener for a language change so we can change the subdirectory to the new language.
* The data parameter will contain the current language (data.from) and new language (data.to).
*
* NOTE: The AVAILABLE_LANGUAGES and SOURCE_LANGUAGE constants need to be updated for the current website.
*/
Localize.on('setLanguage', function(data, event) {
if (localStorage.getItem('loadedLang') !== data.to) {
localStorage.setItem('loadedLang', data.to);
// AVAILABLE_LANGUAGES is the list of language codes used on the site.
const AVAILABLE_LANGUAGES = ["de","en","fr","pl"];
const SOURCE_LANGUAGE = "en";
let pathArr = window.location.pathname.split('/');
let search = window.location.search;
let lang = pathArr[1];
// If there's a supported language in the current pathname, remove it.
if (AVAILABLE_LANGUAGES.includes(lang)) {
pathArr.splice(0,2);
}
let finalPath = pathArr.join('/');
finalPath = finalPath + search;
if (data.to != SOURCE_LANGUAGE) {
window.location.href = urlFilter('/'+data.to+"/"+finalPath);
} else if (data.to === SOURCE_LANGUAGE) {
if (finalPath !== undefined && finalPath != "" && finalPath != "/") {
window.location.href = urlFilter("/"+finalPath);
} else {
window.location.href = urlFilter("/");
}
}
}
}
// Replace any double slashes in the URL with a single slash.
function urlFilter(url) {
return url.replace(/\/+/g, '/');
}
ο»Ώ