Skip to content
haibane84 edited this page Apr 18, 2012 · 11 revisions

Ext's Localization Files

ExtJS 4.x의 압축파일 안에는 locale이라는 폴더가있다. 해당 폴더안에 ext-lang-ko.js가 있는대 파일을 보면 어떻게 한글화가 되는지 알 수가 있다.

Ext.Date.monthNames = [
        "1월",
        "2월",
        "3월",
        "4월",
        "5월",
        "6월",
        "7월",
        "8월",
        "9월",
        "10월",
        "11월",
        "12월"
    ];

    Ext.Date.dayNames = [
        "일",
        "월",
        "화",
        "수",    
        "목",
        "금",
        "토"
    ];

Utilizing Localization

다국어처리를 지원하는 방법으로는 2가지 방법이 있겠다. 하나는 정적으로 적용하는 것이고 하나는 동적으로 적용하는 것이다. 본 문서에서는 동적으로 지원하는 방법에 대하여 기술하겠다.

아래와 같이 기본적인 HTML코드를 작성한다.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Localization example</title>
    <!-- Ext Library Files -->
    <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">
    <script src="ext/ext-all-debug.js"></script>
    <!-- App Scripts -->
    <script src="languages.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <div id="languages"></div>
    <div id="datefield"></div>
</body>
</html>

우리는 두개의 자바스크립트 파일이 있다. 하나는 언어목록을 가지고 있는 파일이고 다른하나는 어플리케이션 파일이다. 또한 두개의 div 태그가 있는대 첫번째는 사용자가 선택할 언어 콤보박스이고 두번째는 data picker용이다.

이제 languages.js를 만들어 보자.

Ext.namespace('Ext.local');

Ext.local.languages = [
    ['af', 'Afrikaans'],
    ['bg', 'Bulgarian'],
    ['ca', 'Catalonian'],
    ['cs', 'Czech'],
    ['da', 'Danish'],
    ['de', 'German'],
    ['el_GR', 'Greek'],
    ['en_GB', 'English (UK)'],
    ['en', 'English'],
    ['es', 'Spanish/Latin American'],
    ['fa', 'Farsi (Persian)'],
    ['fi', 'Finnish'],
    ['fr_CA', 'French (Canadian)'],
    ['fr', 'French (France)'],
    ['gr', 'Greek (Old Version)'],
    ['he', 'Hebrew'],
    ['hr', 'Croatian'],
    ['hu', 'Hungarian'],
    ['id', 'Indonesian'],
    ['it', 'Italian'],
    ['ja', 'Japanese'],
    ['ko', 'Korean'],
    ['lt', 'Lithuanian'],
    ['lv', 'Latvian'],
    ['mk', 'Macedonian'],
    ['nl', 'Dutch'],
    ['no_NB', 'Norwegian Bokmål'],
    ['no_NN', 'Norwegian Nynorsk'],
    ['pl', 'Polish'],
    ['pt_BR', 'Portuguese/Brazil'],
    ['pt_PT', 'Portuguese/Portugal'],
    ['ro', 'Romanian'],
    ['ru', 'Russian'],
    ['sk', 'Slovak'],
    ['sl', 'Slovenian'],
    ['sr_RS', 'Serbian Cyrillic'],
    ['sr', 'Serbian Latin'],
    ['sv_SE', 'Swedish'],
    ['th', 'Thai'],
    ['tr', 'Turkish'],
    ['ukr', 'Ukrainian'],
    ['vn', 'Vietnamese'],
    ['zh_CN', 'Simplified Chinese'],
    ['zh_TW', 'Traditional Chinese']
];

locale폴더안에 제공된 언어들에 대한 리스트를 모두 위의 파일에 넣었다.

Next, we'll start building the application itself. Using the module pattern, we will have four methods: init, onSuccess, onFailure and setup.

다음으로 app.js를 모듈페턴을 이용하여 MultiLangDemo 만들어보겠다.

Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', 'ext/examples/ux/');
Ext.require([
    'Ext.data.*',
    'Ext.tip.QuickTipManager',
    'Ext.form.*',
    'Ext.ux.data.PagingMemoryProxy',
    'Ext.grid.Panel'
]);

Ext.onReady(function() {

    MultiLangDemo = (function() {
        return {
            init: function() {

            },
            onSuccess: function() {

            },
            onFailure: function() {

            },
            setup: function() {

            }
        };
    })();

    MultiLangDemo.init();
});

선택 가능한 언어목록을 콤보박스에 담기위해선 먼저 array store를 만들어야 한다.

var store = Ext.create('Ext.data.ArrayStore', {
    fields: ['code', 'language'],
    data  : Ext.local.languages //from languages.js
});

위에서 우리가 namespace로 지정하였듯이 해당 store의 데이타를 Ext.local.languages로 지정하고 두 필드로 코드와 언어를 지정하였다. 브라우저에서 Ext.local.languages를 콘솔에 찍어보면 어떤 값이 들어있는지 알 수 있다.

이제 init 함수 안에 combobox를 만들어 보자.

var combo = Ext.create('Ext.form.field.ComboBox', {
    renderTo: 'languages',
    store: store,
    displayField: 'language',
    queryMode: 'local',
    emptyText: 'Select a language...',
    hideLabel: true,
    listeners: {
        select: {
            fn: function(cb, records) {
                var record = records[0];
                window.location.search = Ext.urlEncode({"lang":record.get("code")});
            },
            scope: this
        }
    }
});

브라우저를 리플레쉬 하면 아래와 같은 그림을 볼 수 있다. 그림1

컴보박스를 생성하고 난 후 우리는 어떠한 언어가 선택되어 있는지 Ext.urlDecode를 통하여 확인할 것 이다.

var params = Ext.urlDecode(window.location.search.substring(1));

if (params.lang) {
    var url = Ext.util.Format.format('ext/locale/ext-lang-{0}.js', params.lang);

   Ext.Ajax.request({
        url: url,
        success: this.onSuccess,
        failure: this.onFailure,
        scope: this
    });

// check if there's really a language with passed code
var record = store.findRecord('code', params.lang, null, null, null, true);
// if language was found in store, assign it as current value in combobox

    if (record) {
        combo.setValue(record.data.language);
    }
} else {
    // no language found, default to english
    this.setup();
}

Ext.tip.QuickTipManager.init();

우리는 로케이션 파일들을 AJAX 요청으로 로딩할 것 이다. 그래서 해당 파일들은 서버에 업로드 되어져 있어야만 한다. 안그러면 브라우저 보안상의 문제로 로드가 안될것이다.

만약 해당 로케이션 파일들의 로드가 실패할 경우에 대비하여 아래와 같이 Extjs 경고 메시지창을 띄어주도록 한다.

onFailure: function() {
Ext.Msg.alert('Failure', 'Failed to load locale file.');
this.setup();
}

onfailure

onSuccess 메소드는 아래와 같다. 우리는 locale 파일을 확인한 후 setup메소드를 호출할 것이다.

onSuccess: function(response) {
eval(response.responseText);
this.setup();
}

AJAX 호출로 부터 받을 수 있는 파라미터들은 몇가지가 있다. 그중 response의 responseText를 javaScript의 eval 함수로 호출하게 되면 우리는 번역된 문서를 적용하게된다. 즉 어플리케이션에 로컬라이제이션 처리를 적용한 것이다.

이제 setup() 메소드 부분을 보도록 하자.

setup: function() {
Ext.create('Ext.FormPanel', {
    renderTo: 'datefield',
    frame: true,
    title: 'Date picker',
    width: 380,
    defaultType: 'datefield',
    items: [{
        fieldLabel: 'Date',
        name: 'date'
    }]
});
}

이제 켈린터 아이콘을 클릭하여 보면 달력의 달들이 다국어처리가 된 것을 확인할 수 있다.

datepicker

더욱 많은 예제를 위하여 html에는 아래의 3 div를 추가해보자

  	<div id="datefield"></div>
   	<div id="emailfield"></div>
   	<div id="grid"></div>

그리고 각 div에 해당하는 컴포넌트를 적용시켜보자

Ext.create('Ext.FormPanel', {
renderTo: 'emailfield',
labelWidth: 100,
frame: true,
title: 'E-mail Field',
width: 380,
defaults: {
    msgTarget: 'side',
    width: 340
},
defaultType: 'textfield',
items: [{
    fieldlabel: 'Email',
    name: 'email',
    vtype: 'email'
}]

});

var monthArray = Ext.Array.map(Ext.Date.monthNames, function (e) { return [e]; }); var ds = Ext.create('Ext.data.Store', { fields: ['month'], remoteSort: true, pageSize: 6, proxy: { type: 'pagingmemory', data: monthArray, reader: { type: 'array' } } });

Ext.create('Ext.grid.Panel', { renderTo: 'grid', width: 380, height: 203, title:'Month Browser', columns:[{ text: 'Month of the year', dataIndex: 'month', width: 240 }], store: ds, bbar: Ext.create('Ext.toolbar.Paging', { pageSize: 6, store: ds, displayInfo: true }) }); // trigger the data store load ds.load();

기타 컴포넌트들

Conclusion

이번 튜토리얼에서 우리는 각 다른 번역된 로케일 파일들을 ajax로 로드하고 이를 동적으로 적용시켜 보았다. 정적인 경우에는 단지 해당 js을 html에 script로 넣어주기만 하면된다. 하지만 동적으로 구성하여 원하는 로케일 정보를 사용자가 선택하게 할수도 있다. jsp나 asp와 같은 서버기술을 이용하면 더욱 훌륭한 다국어처리가 가능할 수 도 있을거라 기대된다.

Clone this wiki locally