# 模板引擎

function tmpl(str, data) {
  var string =
    "var p = []; p.push('" +
    str
      .replace(/[\r\t\n]/g, "")
      .replace(/<%=(.*?)%>/g, "');p.push($1);p.push('")
      .replace(/<%/g, "');")
      .replace(/%>/g, "p.push('") +
    "');";

  eval(string);

  return p.join("");
}

const temp = `<script type="text/html" id="user_tmpl">
<%for ( var i = 0; i < users.length; i++ ) { %>
    <li>
        <a href="<%=users[i].url%>">
            <%=users[i].name%>
        </a>
    </li>
<% } %>
</script>`;

var users = [
  { name: "Byron", url: "http://localhost" },
  { name: "Casper", url: "http://localhost" },
  { name: "Frank", url: "http://localhost" },
];

console.log(tmpl(temp, users));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Last Updated: 6/27/2023, 7:40:45 PM