→ Edit site languages 에서 사용할 언어 추가하기
→ Activate and show in the language selector가 체크되어있는지 확인하기
※ lwc020ChangeLang.html
<template>
<div class="wrapper">
<p class="sub-title">{label.TodayContent}</p>
<lightning-combobox
options={options}
value={currentValue}
onchange={handleLanguageSelect}
></lightning-combobox>
</div>
</template>
※ lwc020ChangeLang.js
import { LightningElement } from 'lwc';
import activeLanguages from '@salesforce/site/activeLanguages';
import currentLanguage from '@salesforce/i18n/lang';
import basepath from '@salesforce/community/basePath';
import TodayContent from '@salesforce/label/c.TodayContent';
export default class Lwc020ChangeLang extends LightningElement {
label = {
TodayContent,
};
get options() {
return activeLanguages.map((x) => ({ value: x.code, ...x }));
}
get currentValue() {
return currentLanguage;
}
handleLanguageSelect(evt) {
const selectedLanguageCode = evt.detail.value;
// locale is in base path and needs to be replaced with new locale
const newBasePath = this.updateLocaleInBasePath(
basepath,
currentLanguage,
selectedLanguageCode
);
const currentUrl = window.location.pathname;
if (currentUrl) {
const restOfUrl = currentUrl.substring(basepath.length);
window.location.href = window.location.origin + newBasePath + restOfUrl;
} else {
// WARNING: this is a current limitation of Lightning Locker in LWR sites
// Locker must be disabled to reference the global window object
console.warn('Lightning Locker must be disabled for this language picker component to redirect');
}
}
updateLocaleInBasePath(path, oldLocale, newLocale) {
if (path.endsWith('/' + oldLocale)) {
// replace with new locale
return path.replace(new RegExp('/' + oldLocale + '$'), '/' + newLocale);
} else {
// since the default locale is not present in the base path,
// append the new locale
return path + '/' + newLocale;
}
}
}
※ lwc020ChangeLang.css
.wrapper{
width: 100%;
max-width: 800px;
margin: 10px auto;
background-color: #c8d1e9;
padding: 20px 10px;
border-radius: 5px;
min-height: 200px;
}