JavaScript模板引擎用法實例
更新時間:2015年07月10日 17:13:17 作者:優(yōu)雅先生
這篇文章主要介紹了JavaScript模板引擎用法,涉及javascript實現(xiàn)模板的定義與字符替換的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了JavaScript模板引擎用法。分享給大家供大家參考。具體如下:
這里介紹的這個模板引擎寫得短小精悍,非常值得一看
tmpl.js文件如下:
// Simple JavaScript Templating // John Resig - http://ejohn.org/ - 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('');" ); // Function ends // Provide some basic currying to the user return data ? fn(data) : fn; }; })();
index.html文件如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaScript tmpl Use Demo</title> <script type="text/javascript" src="js/jquery.min.js"></script> <script src="./tmpl.js" type="text/javascript"></script> <!-- 下面是模板user_tmpl --> <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"> // 用來填充模板的數(shù)據(jù) var users = [ { url: "http://baidu.com", name: "jxq"}, { url: "http://google.com", name: "william"} ]; $(function() { // 調(diào)用模板引擎函數(shù)將數(shù)據(jù)填充到模板獲得最終內(nèi)容 $("#myUl").html(tmpl("user_tmpl", users)); }); </script> </head> <body> <div> <ul id="myUl"> </ul> </div> </body> </html>
希望本文所述對大家的javascript程序設(shè)計有所幫助。
相關(guān)文章
JavaScript30 一個月純 JS 挑戰(zhàn)中文指南(英文全集)
JavaScirpt30 是 Wes Bos 推出的一個 30 天挑戰(zhàn)。項目免費(fèi)提供了 30 個視頻教程、30 個挑戰(zhàn)的起始文檔和 30 個挑戰(zhàn)解決方案源代碼。目的是幫助人們用純 JavaScript 來寫東西,不借助框架和庫,也不使用編譯器和引用2017-07-07underscore之Collections_動力節(jié)點Java學(xué)院整理
underscore為集合類對象提供了一致的接口。集合類是指Array和Object,暫不支持Map和Set。下面通過本文給大家分享underscore之Collections的相關(guān)知識,需要的的朋友參考下吧2017-07-07BootStrap select2 動態(tài)改變值的方法
這篇文章主要介紹了BootStrap select2 動態(tài)改變值的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-02-02JavaScript回調(diào)(callback)函數(shù)概念自我理解及示例
此文適合JavaScript入門級選手閱讀,在JavaScript里什么叫Callback“回調(diào)函數(shù)”,把方法b當(dāng)做一個參數(shù)傳遞個方法a,當(dāng)方法a執(zhí)行完后執(zhí)行另外一個指定函數(shù)(這里是b函數(shù)),感興趣的朋友可以了解下哈2013-07-07