自定义模板引擎

434 阅读1分钟

自己要编一个类似于jsx的语法模板引擎,参考了一些模板引擎代码,这里看到的是比较简单的模板引擎实现代码,这里已经注明出处,望原作者谅解!

// Simple JavaScript Templating
// John Resig - https://johnresig.com/ - MIT Licensed
(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
  cache[str] = cache[str] ||
    tmpl(document.getElementById(str).innerHTML) :

  // Generate a reusable function that will serve as a template
  // generator (and which will be cached).
  new Function("obj",
    "var p=[],print=function(){p.push.apply(p,arguments);};" +

    // Introduce the data as local variables using with(){}
    "with(obj){p.push('" +

    // Convert the template into pure JavaScript
    str
      .replace(/[\r\t\n]/g, " ")
      .split("<%").join("\t")
      .replace(/((^|%>)[^\t]*)'/g, "$1\r")
      .replace(/\t=(.*?)%>/g, "',$1,'")
      .split("\t").join("');")
      .split("%>").join("p.push('")
      .split("\r").join("\\'")
  + "');}return p.join('');");

// Provide some basic currying to the user
return data ? fn( data ) : fn;
  };
})();

使用起来也就三步走。

第一步,将上边的代码粘贴到JS作用域最开始部分。 第二步,随便写一个模版。

<script id="hello_template">
  <h2><%=message%></h2>
  <ul>
    <% for(var userIndex in users) { %>
      <li>#<%=users[userIndex]._id%>: <%=users[userIndex].name%></li>
    <% } %>
  </ul>
</script>

第三布,按照格式 tmpl(TEMPLATE_HTML_ID | TEMPLATE_HTML_TEXT, INPUT_DATA) 调用模版。

TEMPLATE_HTML_TEXT 工作方式

var html = tmpl('<h1><%=message%></h1>', {message: 'hello'});

console.log(html);
1
2
3
TEMPLATE_HTML_ID 工作方式

var html = tmpl('hello_template', {
 message: 'hello, world.',
  users: [
    {_id: 0, name: 'robin'},
    {_id: 1, name: 'alex'}
  ]
});

console.log(html);

慢慢领悟,很有意思。

作者:蜜汁小强 来源:CSDN 原文:blog.csdn.net/wxqee/artic…

版权声明:本文为博主原创文章,转载请附上博文链接!