Underscore template
/********************************************************************* * Underscore template * 说明: * 在找JavaScript数据处理lib的时候,找到Underscore,细读一下其开发文档, * 发现里面有template处理,对比了一下Handlebars,感觉Underscore更适合目前使 * 用,主要是目前足够了。 * * 2017-8-28 深圳 龙华樟坑村 曾剑锋 ********************************************************************/ 一、参考文档: 1. Underscore http://underscorejs.org/ 2. Underscore template http://www.bootcss.com/p/underscore/#template 3. UnderscoreJS精巧而强大工具包 http://blog.fens.me/nodejs-underscore/ 4. underscore templates - JSFiddle https://jsfiddle.net/casiano/LS384/ 二、template demo: <!-- Install jQuery and underscore --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script> <!-- Create your template --> <script type="foo/bar" id='usageList'> <table cellspacing='0' cellpadding='0' border='1' > <thead> <tr> <th>Id</th> <th>Name</th> </tr> </thead> <tbody> <% // repeat items _.each(items,function(item,key,list){ // create variables var f = item.name.split("").shift().toLowerCase(); %> <tr> <!-- use variables --> <td><%= key %></td> <td class="<%= f %>"> <!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') --> <h3><%- item.name %></h3> <p><%- item.interests %></p> </td> </tr> <% }); %> </tbody> </table> </script> <!-- Create your target --> <div id="target"></div> <!-- Write some code to fetch the data and apply template --> <script type="text/javascript"> var items = [ {name:"Alexander", interests:"creating large empires"}, {name:"Edward", interests:"ha.ckers.org <\nBGSOUND SRC=\"javascript:alert('XSS');\">"}, {name:"..."}, {name:"Yolando", interests:"working out"}, {name:"Zachary", interests:"picking flowers for Angela"} ]; var template = $("#usageList").html(); $("#target").html(_.template(template,{items:items})); </script>