代码改变世界

一个轻量级 Javascript 模板引擎 front.js【二】

2013-05-21 23:49  音乐让我说  阅读(1919)  评论(0编辑  收藏  举报

 

项目地址:https://github.com/myst729/front.js

主要代码:

 front.js

var front = function(source, target, template) {
  var data = Array.isArray(source) ? source : [source];
  var html = "";

  data.forEach(function(el) {
    var tmpl = template.replace(/@if\{\{(\w+)\}\}([\s\S]+?)(@else([\s\S]+?))?@endif/g, function($, $1, $2, $3, $4) {
      return el[$1] ? $2 : ($3 ? $4 : "");
    });

    html += tmpl.replace(/\{\{(\w+)\}\}/g, function($, $1) {
      return ($1 in el) ? el[$1] : $;
    });
  });

  target.innerHTML = html;
};

Demo 代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>front.js</title>
    <style>
      body { font-family: Georgia, serif; }
      h2, h3, p, div { margin: 10px; overflow: hidden; }
      .person { border: 1px solid #ccc; margin: 5px; padding: 5px 10px; width: 200px; float: left; }
    </style>
  </head>
  <body>

    <h2>demo 1</h2>
    <div id="target1"></div>
    <h2>demo 2</h2>
    <div id="target2"></div>
    <h2>demo 3</h2>
    <div id="target3"></div>

    <script type="text/template" id="template">
      <div class="person">
        <h3>{{name}}</h3>
        <p>Age: {{age}}</p>
        @if{{sex}}
        <p>Sex: {{sex}}</p>
        @endif
        @if{{job}}
        <p>Job: {{job}}</p>
        @else
        <p>Available for hire</p>
        @endif
      </div>
    </script>

    <script src="front.js"></script>
    <script>
      var source1 = {name: "Mike", age: 32, job: "Web Developer"};
      var target1 = document.getElementById("target1");
      var template1 = '<div class="person"><h3>{{name}}</h3><p>Age: {{age}}</p><p>Job: {{job}}</p></div>';
      front(source1, target1, template1);

      var source2 = [{name: "Bob", age: 24, sex: "male"}, {name: "Nick", age: 27, sex: "male"}, {name: "Jane", age: 25, sex: "female"}];
      var target2 = document.getElementById("target2");
      var template2 = '<div class="person"><h3>{{name}}</h3><p>Age: {{age}}</p><p>Sex: {{sex}}</p></div>';
      front(source2, target2, template2);

      var source3 = [{name: "Bob", age: 24, sex: "male", job: "Web Developer"}, {name: "Nick", age: 27, job: "Architect"}, {name: "Jane", age: 25, sex: "female"}];
      var target3 = document.getElementById("target3");
      var template3 = document.getElementById("template").innerHTML;
      front(source3, target3, template3);
    </script>
  </body>
</html>


效果图

 也许你还会喜欢:

自定义 Javascript 模板规则,打造轻量级模板引擎

一个简单的 JavaScript 模板引擎

实例演示 kino.razor (前端 Javascript 模板工具)的使用

谢谢浏览!