码迷,mamicode.com
首页 > Web开发 > 详细

关于js模板技术,使用requireJS定义模块(二)

时间:2015-07-31 13:16:52      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

昨天编写了第一版的模板标签替换代码,发现有很多不足的地方,不足内容如下:

1:正则无法匹配模板中存在的空格问题

2:无法删除属性项中不存在的标签

根据昨天的不足,经过修正后,新的模板替换方法如下:

/**
 * @Author Dike.Li
 * @Date 2015/7/30
 * @Description Template Label Replace
 */
define(function (require, exports, module) {
    /**
     * 要求模板中的{id}标签与option中的属性{id:123}一致
     * @param temp 模板
     * @param option 属性设置
     * @returns {*}
     * @constructor
     */
    var Template = function (temp, option) {

        /**
         * 提取模板中 XXX=‘{XXX}‘ || XXX="{XXX}"
         * @type {RegExp}
         */
        var regExp = new RegExp(‘[a-zA-Z]+[\\s]*=[\\s]*[\"\‘]\\{[^\\{\\}]+\\}[\"\‘]‘, ‘\g‘);

        /**
         * 提取属性正则表达式 XXX
         * @type {RegExp}
         */
        var regExpAttribute = new RegExp(‘[a-zA-Z]+‘, ‘\g‘);

        /**
         * 提取标签正则表达式 {XXX}
         * @type {RegExp}
         */
        var regExpLable = new RegExp(‘\\{[^\\{\\}]+\\}‘, ‘\g‘);

        /**
         * 提取 XXX=‘{XXX}‘ || XXX="{XXX}" 格式的数组
         * @type {Array|{index: number, input: string}|*}
         */
        var alArr = temp.match(regExp);

        /**
         * 根据option中的属性配置项翻译模板内容,并将不存在的标签删除
         */
        for (var al in alArr) {
            /**
             * 获取属性
             */
            var attribute = alArr[al].match(regExpAttribute)[0];

            /**
             * 获取标签
             */
            var label = alArr[al].match(regExpLable)[0];

            if (typeof(option[attribute]) === ‘undefined‘ ||
                option[attribute] === null ||
                option[attribute] === ‘null‘ ||
                option[attribute] === ‘‘) {
                temp = temp.replace(alArr[al], ‘‘);
                continue;
            }

            temp = temp.replace(label, option[attribute]);
        }

        /**
         * 返回解析后的模板
         * @returns {*}
         */
        Template.prototype.getTemp = function () {
            return temp;
        };
    };
    module.exports = Template;
});


关于js模板技术,使用requireJS定义模块(二)

标签:

原文地址:http://my.oschina.net/u/2349331/blog/486029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!