Solo  当前访客:1 开始使用

精简js模板引擎学习


代码:

var TemplateEngine = function(html, options) {
    var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0;
    var add = function(line, js) {
        js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
        return add;
    }
    while(match = re.exec(html)) {
        add(html.slice(cursor, match.index))(match[1], true);
        cursor = match.index + match[0].length;
    }
    add(html.substr(cursor, html.length - cursor));
    code += 'return r.join("");';
    return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
}

测试:

TemplateEngine("<span><%this.name%></span>",{name:22222})
TemplateEngine("<%if(this.age<20){%><span><%this.name%></span><%}else{%><strong><%this.name%><strong><%}%>",[{name:22222,age:33},{name:123,age:12}])

知识点

new Function ([arg1[, arg2[, ...argN]],] functionBody)

通过Function构造器创建,

按MDN的描述,这种方式相对效率较低


标题:精简js模板引擎学习
作者:hugh0524
地址:https://blog.uproject.cn/articles/2016/09/27/1474959757829.html

, , , 0 0