主要弄一下基於jQuery.i18n.properties 實現前端頁面的資源國際化這個問題,也就是將頁面中的顯示中文的地方都變成可以根據用戶選擇的語言來變化的。網上也有很多js專門做這個國際化的,最終我們選擇了jQuery.i18n.properties來實現。
先來copy一段關於jQuery.i18n.properties 的說明哈。
jQuery.i18n.properties是一款輕量級的jQuery國際化插件,能實現Web前端的國際化。
國際化英文單詞爲:Internationalization,又稱i18n,“i”爲單詞的第一個字母,“18”爲“i”和“n”之間單詞的個數,而“n”代表這個單詞的最後一個字母。jQuery.i18n.properties採用.properties文件對JavaScript進行國際化。jQuery.i18n.properties插件首先加載默認的資源文件(strings.properties),然後加載針對特定語言環境的資源文件(strings_zh.properties),這就保證了在未提供某種語言的翻譯時,默認值始終有效。
廢話少說,直接上代碼吧(just demo)!
第一步:
下載必須的js文件
jquery.i18n.properties.js
jquery.js
第二步:
新建demo靜態頁面index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title class="i18n" name='title'></title>
<meta id="i18n_pagename" content="index-common">
<meta name="viewport" content="width=device-width">
<meta name="keywords" content="" />
<meta name="description" content=""/>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<div class="lan">
<div class="lan1"><label class="i18n" name="lan"></label></div>
<div class="lan2">
<select id="language">
<option value="zh-CN">中文簡體</option>
<option value="zh-TW">中文繁體</option>
<option value="en">English</option>
</select>
</div>
</div>
<br>
<hr>
<div><label class="i18n" name="hellomsg1"></label><label class="i18n" name="hellomsg2"></label></div><br>
<div><label class="i18n" name="commonmsg1"></label><label class="i18n" name="commonmsg2"></label></div><br>
<div>
<input type="search" class="i18n-input" selectname="searchPlaceholder" selectattr="placeholder">
</div>
<script src="js/jquery.js"></script>
<!-- 加載語言包文件 -->
<script src="js/jquery.i18n.properties-min-1.0.9.js"></script>
<script src="js/language.js"></script>
</body>
</html>
說明:
1、meta id=”i18n_pagename” content=”index-common” 這裏面的index-common寫法,這裏是引 入了兩個資源文件index和common,這樣做的好處就是,我們可以把公用部分的資源文件放到common裏面,例如頁頭,頁腳等,而且不需在每個頁面都複製這部分內容,當共有內容有所變化,只需要修改common.properties就可以全部修改啦。
2、獲取方式一:label class=”i18n” name=”hellomsg1”這裏面class=”i18n”寫法,下邊在js裏面我們可以根據類選擇器獲取需要國際化的地方,然後name=”hellomsg1”這裏面的hellomsg1跟資源文件裏面的key保持一致。獲取方式二:input type=”search” class=”i18n-input” selectname=”searchPlaceholder” selectattr=”placeholder”這裏面的class=”i18n-input”寫法,跟上邊的區別就是可以給html標籤的任何屬性可以賦值,例如placeholder,name,id什麼的都可以,selectattr=”placeholder”裏面的placeholder就是要賦值的屬性,selectname=”searchPlaceholder”裏面的searchPlaceholder跟資源文件裏面的key保持一致。
第三步:
配置language.js文件
/**
* cookie操作
*/
var getCookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var s = [cookie, expires, path, domain, secure].join('');
var secure = options.secure ? '; secure' : '';
var c = [name, '=', encodeURIComponent(value)].join('');
var cookie = [c, expires, path, domain, secure].join('')
document.cookie = cookie;
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
/**
* 獲取瀏覽器語言類型
* @return {string} 瀏覽器國家語言
*/
var getNavLanguage = function(){
if(navigator.appName == "Netscape"){
var navLanguage = navigator.language;
return navLanguage.substr(0,2);
}
return false;
}
/**
* 設置語言類型: 默認爲中文
*/
var i18nLanguage = "zh-CN";
/*
設置一下網站支持的語言種類
*/
var webLanguage = ['zh-CN', 'zh-TW', 'en'];
/**
* 執行頁面i18n方法
* @return
*/
var execI18n = function(){
/*
獲取一下資源文件名
*/
var optionEle = $("#i18n_pagename");
if (optionEle.length < 1) {
console.log("未找到頁面名稱元素,請在頁面寫入\n <meta id=\"i18n_pagename\" content=\"頁面名(對應語言包的語言文件名)\">");
return false;
};
var sourceName = optionEle.attr('content');
sourceName = sourceName.split('-');
/*
首先獲取用戶瀏覽器設備之前選擇過的語言類型
*/
if (getCookie("userLanguage")) {
i18nLanguage = getCookie("userLanguage");
} else {
// 獲取瀏覽器語言
var navLanguage = getNavLanguage();
if (navLanguage) {
// 判斷是否在網站支持語言數組裏
var charSize = $.inArray(navLanguage, webLanguage);
if (charSize > -1) {
i18nLanguage = navLanguage;
// 存到緩存中
getCookie("userLanguage",navLanguage);
};
} else{
console.log("not navigator");
return false;
}
}
/* 需要引入 i18n 文件*/
if ($.i18n == undefined) {
console.log("請引入i18n js 文件")
return false;
};
/*
這裏需要進行i18n的翻譯
*/
jQuery.i18n.properties({
name : sourceName, //資源文件名稱
path : 'i18n/' + i18nLanguage +'/', //資源文件路徑
mode : 'map', //用Map的方式使用資源文件中的值
language : i18nLanguage,
callback : function() {//加載成功後設置顯示內容
var insertEle = $(".i18n");
console.log(".i18n 寫入中...");
insertEle.each(function() {
// 根據i18n元素的 name 獲取內容寫入
$(this).html($.i18n.prop($(this).attr('name')));
});
console.log("寫入完畢");
console.log(".i18n-input 寫入中...");
var insertInputEle = $(".i18n-input");
insertInputEle.each(function() {
var selectAttr = $(this).attr('selectattr');
if (!selectAttr) {
selectAttr = "value";
};
$(this).attr(selectAttr, $.i18n.prop($(this).attr('selectname')));
});
console.log("寫入完畢");
}
});
}
/*頁面執行加載執行*/
$(function(){
/*執行I18n翻譯*/
execI18n();
/*將語言選擇默認選中緩存中的值*/
$("#language option[value="+i18nLanguage+"]").attr("selected",true);
/* 選擇語言 */
$("#language").on('change', function() {
var language = $(this).children('option:selected').val()
console.log(language);
getCookie("userLanguage",language,{
expires: 30,
path:'/'
});
location.reload();
});
});
說明: 這個js文件寫的比較詳細有註釋,大家一看應該就能懂,大致的就是第一次進來時,會根據瀏覽器的語言選擇默認語言,然後用戶每次選擇不同的語言,會將選擇的語言存入cookie,下一次進入取cookie裏面的語言,核心i18n代碼在 jQuery.i18n.properties({…})這裏面就是給頁面需要國際化的地方賦值。
第四步:
新建不用語言的資源文件index.properties,common.properties
zh-CN/index.properties
title=i18n資源國際化
lan=語言選擇:
hellomsg1=首頁消息:
hellomsg2=資源國際化!這是首頁消息!
searchPlaceholder=請輸入搜索信息
zh-CN/common.properties
commonmsg1=通用消息:
commonmsg2=資源國際化!這是通用消息哦!
zh-TW/index.properties
title=i18n資源國際化
lan=語言選擇:
hellomsg1=首頁消息:
hellomsg2=資源國際化! 這是首頁消息!
searchPlaceholder=請輸入搜索信息
zh-TW/common.properties
commonmsg1=通用消息:
commonmsg2=資源國際化!這是通用消息哦!
en/index.properties
title=i18n Resource Internationalization
lan=Language:
hellomsg1=Index message:
hellomsg2=Hello word! This is index message!
searchPlaceholder=Please input serach information
en/common.properties
commonmsg1=Common message:
commonmsg2=This is common message!
注意:這裏我沒有按照jquery.i18n.properties上邊那種strings.properties,strings_zh.properties寫法寫,我覺得把資源文件按語言類型文件夾劃分,更直觀些,故而將所有中文簡體放在zh-CN下邊,所有中文繁體放在zh-TW下邊,英語放在en下邊。會導致它每次都會去請求index_zh.properties,出現404請求錯誤,不過沒啥大影響啦!
大功告成!
來幾張截圖,看下效果如何!(頁面有點醜呵,不影響啦!)
中文簡體
中文繁體
英語
demo 項目源碼已上傳到 CSDN Download
demo 項目源碼地址:基於jQuery.i18n.properties 實現前端頁面的資源國際化 Demo 源碼