如果新項目要做系統國際化, 時下熱門的任何一種技術選型都有成熟的方案,比如:
- vue + vue-i18n
- angular + angular-translate
- react + react-intl
但是老項目的國際化幾乎是jquery + jquery.i18n.properties這種方案. 那么我們就來看看這種方案是如何實現的.
一. 引入必要的 js 文件
在項目中添加如下目錄結構:
<script src="js/jquery.min.js"></script>
<script src="js/jquery.i18n.properties-1.0.9.js"></script>
二. 資源文件准備
i18n/resource/common.properties
name='姓名'
placeholder='請輸入電話號碼'
login='登錄'
i18n/resource/common_en.properties
name='name'
placeholder= 'Please enter phone number'
login='login'
三. 標簽賦值
一般情況下,我們標簽里面的內容如果要做國際化,需要使用 $('#id').text($.i18n.prop('proName')); 來給標簽賦值,現在問題來了,我們開發一個界面,有很多地方都需要去做國際化,我們總不能這樣每一個頁面每一個標簽通過這種方式去賦值吧,這樣工作量不是一點大,於是乎博主想,有沒有一種比較好的通用的解決方案去給這些需要做國際化的標簽統一賦值呢。html的data屬性似乎是一個不錯的選擇!它具有可讀性強、可維護性強、兼容jquery的data()方法等優點。比如我們修改國際化組件的方法如下
<script>
$(function(){
jQuery.i18n.properties({
name : 'common', //資源文件名稱
path : '/i18n/resource/', //資源文件路徑
mode : 'map', //用Map的方式使用資源文件中的值
callback : function() {
console.log("i18n賦值中...");
try {
//初始化頁面元素
$('[data-i18n-placeholder]').each(function () {
$(this).attr('placeholder', $.i18n.prop($(this).data('i18n-placeholder')));
});
$('[data-i18n-text]').each(function () {
//如果text里面還有html需要過濾掉
var html = $(this).html();
var reg = /<(.*)>/;
if (reg.test(html)) {
var htmlValue = reg.exec(html)[0];
$(this).html(htmlValue + $.i18n.prop($(this).data('i18n-text')));
}
else {
$(this).text($.i18n.prop($(this).data('i18n-text')));
}
});
$('[data-i18n-value]').each(function () {
$(this).val($.i18n.prop($(this).data('i18n-value')));
});
}
catch(ex){ }
console.log("i18n寫入完畢");
}
});
});
</script>
通過data屬性獲取標簽,然后對每個標簽通過對應的data-i18n-屬性
進行國際化賦值即可,這里暫時定義了三種類型data-i18n-placeholder
、data-i18n-text
、data-i18n-value
的屬性,如果有其他需求,可以增加其他類型。
然后看下我們html頁面的使用
<p data-i18n-text='name'></p>
<input type="text" data-i18n-placeholder="placeholder">
<input type="button" data-i18n-value="login"></input>
這樣不用寫一句標簽的賦值代碼,即可對標簽進行國際化
四. 最終效果
- 中文環境下:
- 英文環境下: