简单的 js 模版引擎

时间:2019-07-04
本文章向大家介绍简单的 js 模版引擎,主要包括简单的 js 模版引擎使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

简单的 js 模版引擎

var tplEngine = function(tpl, data) {
    var reg = /<%([^%>]+)?%>/g, 
        regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, 
        code = 'var r=[];\n', 
        cursor = 0;

    var add = function(line, js) {
        js? (code += line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n') :
            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
        return add;
    }
    while(match = reg.exec(tpl)) {
        add(tpl.slice(cursor, match.index))(match[1], true);
        cursor = match.index + match[0].length;
    }
    add(tpl.substr(cursor, tpl.length - cursor));
    code += 'return r.join("");';
    return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
};

var template = `
My skills:
<%if(this.showSkills) {%>
  <%for(var index in this.skills) {%>
    <a href="#"><%this.skills[index]%></a>
  <%}%>
<%} else {%>
  <p>none</p>
<%}%>
`
console.log(tplEngine(template, {
    skills: ["js", "html", "css"],
    showSkills: true
}));

原文地址:https://www.cnblogs.com/daysme/p/11134635.html