在Javascript中实现模版编译

2018-11-30 09:29:45

在Javascript中实现模版编译

原文(阮一峰):
http://es6.ruanyifeng.com/#docs/string#%E5%AE%9E%E4%BE%8B%EF%BC%9A%E6%A8%A1%E6%9D%BF%E7%BC%96%E8%AF%91

模板编译方法

  1. function compile(template){
  2. const evalExpr = /<%=(.+?)%>/g;
  3. const expr = /<%([\s\S]+?)%>/g;
  4. template = template.replace(evalExpr, '`); \n echo( $1 ); \n echo(`').replace(expr, '`); \n $1 \n echo(`');
  5. template = 'echo(`' + template + '`);';
  6. let script =
  7. ` (function parse(data){
  8. let output = "";
  9. function echo(html){
  10. output += html;
  11. }
  12. ${ template }
  13. return output;
  14. })
  15. `;
  16. return script;
  17. }

编译 & 填充模板

<% ... %>中执行js代码
在·<%= ...%>输出变量(jsp的感觉)

  1. let template = `
  2. <ul>
  3. <%for (let i of users){%>
  4. <li><%=i.name%>,<%=i.age%></li>
  5. <%}%>
  6. </ul>
  7. `;
  8. //编译
  9. let parse = eval(compile(template));
  10. //models
  11. let users = [{name:'KevinBlandy',age:23},{name:'Litch',age:24}];
  12. //填充
  13. let result = parse(users);
  14. console.log(result);

输出结果

  1. <ul>
  2. <li>KevinBlandy,23</li>
  3. <li>Litch,24</li>
  4. </ul>

1
2
0

添加评论

正在回复:
取消
3
1
2
0