LWC에서 LWR Site 언어 바꾸기

ahncheer·2022년 9월 30일
0

LWC & LWR

목록 보기
16/45

1. 코드 작성 전 세팅


→ Edit site languages 에서 사용할 언어 추가하기
→ Activate and show in the language selector가 체크되어있는지 확인하기

2. 코드 작성

※ 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;
}

3. 결과 확인

4. 참고한 링크

https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_community_info

profile
개인 공부 기록용.

0개의 댓글