本文分享一個短小精悍的 JavaScript 模板引擎用法,非常值得一看,供大家參考。
// Simple JavaScript Templating
// John Resig - https://ejohn.org/ - MIT Licensed
(function () {
var cache = {};
this.tmpl = function tmpl(str, data) {
// 判斷是拿到模板,還是需要載入模板,並確保結果被快取
var fn = !/\W/.test(str)
? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML)
:
// 產生一個可重複使用的函式作為模板產生器(並快取)
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// 用 with(){} 把資料作為區域變數引入
"with(obj){p.push('" +
// 把模板轉成純 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('');"
);
// 提供基本的 currying 給使用者
return data ? fn(data) : fn;
};
})(); <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>
<script type="text/javascript">
// 用來填充模板的資料
var users = [
{ url: "https://baidu.com", name: "jxq" },
{ url: "https://google.com", name: "william" }
];
$(function () {
// 呼叫模板引擎函式將資料填入模板取得最終內容
$("#myUl").html(tmpl("user_tmpl", users));
});
</script>這個由 John Resig 撰寫的模板引擎,把 <% %> 邏輯與 <%= %> 輸出的模板,編譯成可快取、可重複使用的函式,用起來輕量又高效,很適合小專案使用。