简单的 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
}));

猜你喜欢

转载自www.cnblogs.com/daysme/p/11134635.html