일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
- java
- IEnumerator
- 백준
- jquery
- 백준11727번
- 동적프로그래밍
- 알고리즘풀이
- cocoscreator
- 2xn타일링
- Enumerable
- 백준알고리즘
- javascript
- IEnumerable
- 1로만들기
- yield
- c#문법
- DP
- Enumerator
- foreach
- i18n
- c#
- json
- A*알고리즘
- html
- 2x1타일링
- Atar알고리즘
- 백준11726번
- 동적계획법
- 다국어
- 알고리즘
- Today
- Total
Memento's Programming
[Jquery i18n] 다국어 지원 웹 개발, java .properties 파일을 JSON파일로 바꾸기 본문
요즘 회사에서 다국어를 지원하는 웹을 개발하고 있다.
기존에는 서버를 호출하여 페이지를 뿌려주는 방식으로 개발하고 있었는데 (jsp사용) 최근에는 정적인 페이지로 바꾸면서 다국어 지원이 어려워졌다.
기존 다국어 관련 properties 파일 구조이다.
ㄴ resources
ㄴ messages.properties(default)
ㄴ messages_ko.properties
ㄴ messages_en.properties
ㄴ messages_ja.properties
ㄴ messages_zh.properties
각 프로퍼티 파일 안에는 다음과 같은 형태로 이루어져 있다.
message.properties
title=제목
message.hello=안녕
messages_en.properties
title=title
message.hello=hi
먼저 서버에서 다국어 지원을 하는 것이 아닌 웹 페이지에서 지원해야해서 properties 파일을 json 파일로 바꾸는 작업을 했다.
public void convertPropertiesToJson() {
Map<String, String> jsonList = new HashMap<>();
String[] countryList = {"", "en", "ja", "ko", "zh"}; // properties 국가 리스트
for (String country : countryList) {
String propertiesFile = (country.equals("") ? "messages" : "messages_") + country + ".properties";
String propertiesToJson = new PropertiesToJsonConverter().convertPropertiesFromFileToJson(localeBaseUrl + propertiesFile);
jsonList.put(country, propertiesToJson);
}
JSONParser parser = new JSONParser();
try {
for (String key : jsonList.keySet()) {
Object obj = parser.parse(jsonList.get(key)); // jsonObject
JSONObject jsonObj = (JSONObject) obj; //to JSONObject
String uploadPath = uploadUrl + (key.equals("") ? "messages" : "messages-") + key + ".json";
File file = new File(uploadPath);
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
System.out.println("Writing JSON object to file");
System.out.println("-----------------------");
System.out.print(jsonObj);
fileWriter.write(jsonObj.toJSONString());
fileWriter.flush();
fileWriter.close();
}
} catch (ParseException | IOException e) {
e.printStackTrace();
}
}
사전에 지정한 localBaseUrl 하위에 json파일이 생성되었다. 나는 project-root/s3/json 하위에 파일을 생성하였다.
이렇게 만든 json 파일들을 s3에 업로드하고 이제 i18n에 대해 리서치를 하기 시작했다.
i18n
국제화라는 단어인 Internationalization의 첫글자와 마지막 글자인 I와 N 사이에 18글자가 들어간다는 의미로 I18N이라고 표기한다고 한다.
우리는 국제화를 통해 텍스트를 적은 비용으로 번역할 수 있다.
- 공식 사이트 : https://www.i18next.com/
- Github : https://github.com/i18next/i18next
- CDN : http://cdnjs.com/libraries/i18next
- i18next-node : https://github.com/i18next/i18next-node
i18next는 i18n을 자바스크립트 상에서 사용할 수 있도록 제작된 라이브러리이다.
i18n은 다루기는 어렵지 않은데 문서에 적힌 경로에서 다운로드 받으면 자꾸 function이 아니라나 뭐라나.
그래서 한참을 헤맨 끝에 http://i18next.github.io/i18next/ 에서 i18next를 다운로드 받았다.
다음과 같이 html를 작성하면 html 태그 내에 data-i18n로 정의된 태그를 찾아서 json 값으로 태그 내의 text를 변환한다. (그대로 타이핑하면 에러가 날 것이다. lang를 쿼리스트링으로 받아오는데 그 부분은 밑의 스크립트에서 제외되어 있다.)
<body>
<div>
<h1 data-i18n="message.hello">안녕</h1>
</div>
</body>
<script>
$.i18n.init({
load : 'unspecific',
lng : lang,
fallbackLng : 'en', // 실패할 경우 언어
resGetPath : '../../lang/messages-__lng__.json', // 위에서 설정한 lng
useDataAttrOptions : true,
}, function(t) {
$('html').i18n();
});
</script>
설명이 조금 부족한 것 같아 자세하게 설명하면 h1의 data-i18n속성의 "message.hello"는 "hi"라고 미리 json파일에 정의되어 있는 값이다.
messages-en.json
message: {
hello: "hi"
}
따라서 lang을 en이라고 설정하면 h1에는 안녕 대신 hi가 노출될 것이다.
이외에도 fallbackLng를 설정하면 lang가 잘못된 값이 들어왔을 경우 기본 en값으로 설정해서 messages-en.json을 가져오게 된다.
만약 fallbackLng를 설정하지 않고 잘못된 값이 들어왔을 경우에는 기존에 h1 태그 내에 정의했던 안녕이 그대로 노출된다.
이 외에도 다양한 설정값과 함수를 지원하니 문서를 확인하면 더욱 다양하고 효과적이게 사용할 수 있을 것이다.