jquery.i18n.properties前端國際化方案

若是新項目要作系統國際化, 時下熱門的任何一種技術選型都有成熟的方案,好比:html

  1. vue + vue-i18n
  2. angular + angular-translate
  3. react + react-intl

可是老項目的國際化幾乎是jquery + jquery.i18n.properties這種方案. 那麼咱們就來看看這種方案是如何實現的.vue

一. 引入必要的 js 文件

在項目中添加以下目錄結構:react

Exb3se.png

<script src="js/jquery.min.js"></script>
<script src="js/jquery.i18n.properties-1.0.9.js"></script>

二. 資源文件準備

i18n/resource/common.propertiesjquery

name='姓名'
placeholder='請輸入電話號碼'
login='登陸'

i18n/resource/common_en.propertiesthis

name='name'
placeholder= 'Please enter phone number'
login='login'

三. 標籤賦值

通常狀況下,咱們標籤裏面的內容若是要作國際化,須要使用 $('#id').text($.i18n.prop('proName')); 來給標籤賦值,如今問題來了,咱們開發一個界面,有不少地方都須要去作國際化,咱們總不能這樣每個頁面每個標籤經過這種方式去賦值吧,這樣工做量不是一點大,因而乎博主想,有沒有一種比較好的通用的解決方案去給這些須要作國際化的標籤統一賦值呢。html的data屬性彷佛是一個不錯的選擇!它具備可讀性強、可維護性強、兼容jquery的data()方法等優勢。好比咱們修改國際化組件的方法以下code

<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-placeholderdata-i18n-textdata-i18n-value的屬性,若是有其餘需求,能夠增長其餘類型。
而後看下咱們html頁面的使用htm

<p data-i18n-text='name'></p>
<input type="text" data-i18n-placeholder="placeholder">
<input type="button" data-i18n-value="login"></input>

這樣不用寫一句標籤的賦值代碼,便可對標籤進行國際化blog

四. 最終效果

  • 中文環境下:

Ex7vh6.png

  • 英文環境下:

Ex7jtx.png

相關文章
相關標籤/搜索