jquery.i18n.properties前端国际化方案

如果新项目要做系统国际化, 时下热门的任何一种技术选型都有成熟的方案,比如:

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

但是老项目几乎都说的是jquery + jquery.i18n.properties这种方案. 那么我们就来看看这种方案是如何实现的.

一. 引入必要的 js 文件

在项目中添加如下目录结构:

Exb3se.png

<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-placeholderdata-i18n-textdata-i18n-value的属性,如果有其他需求,可以增加其他类型。
然后看下我们html页面的使用

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

这样不用写一句标签的赋值代码,即可对标签进行国际化

四. 最终效果

  • 中文环境下:

Ex7vh6.png

  • 英文环境下:

Ex7jtx.png

猜你喜欢

转载自www.cnblogs.com/liuyishi/p/10896105.html