<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>handlebars_v2.0_demo</title> <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script> <script type="text/javascript" src="js/handlebars-v2.0.0.js"></script> </head> <div id="demo"> </div> <script id="user-template" type="text/x-handlebars-template"> <h1>{{time}}</h1> {{#each user}} <p> {{#if name}} {{@index}}. 姓名:{{name}} 年龄:{{age}} 成年:{{Adult age}} {{#Compare age 18 }} 大于等于18岁 {{else}} 小于18岁 {{/Compare}} 记录时间:{{../../time}} {{/if}} </p> {{/each}} </script> <script> $(function(){ var data = { user:[{ name:"sky", age:28 },{ name:"json", age:10 },{ age:2 },{ name:"joy", age:18 }], time:"2014-12-26" } var myTemplate = Handlebars.compile($("#user-template").html()); Handlebars.registerHelper("Adult",function(age){return (age >= 18) ? "成年" : "未成年";}); Handlebars.registerHelper("Compare",function(i1,i2,options){if(i1>=i2) {return options.fn(this); }else {return options.inverse(this);}}); $("#demo").html(myTemplate(data)); }) </script> <div id="demo2"> </div> <script id="class-template" type="text/x-handlebars-template"> {{#each this}} <dl> <dt>{{class}} 共有{{group.count}}个小组 班长:{{student.[0].name}}</dt> {{#with student}} {{#each this}} <dd>{{name}}</dd> {{/each}} {{/with}} </dl> {{/each}} </script> <script> $(function(){ var data2 = [ { class:"一年级", student:[{ name:"王晓飞" },{ name:"陈扇" },{ name:"理查德" }], group:{ count:6 } }, { class:"二年级", student:[{ name:"朱暖" },{ name:"张坚庭" },{ name:"刘海得" }], group:{ count:8 } }] var myTemplate = Handlebars.compile($("#class-template").html()); $("#demo2").html(myTemplate(data2)); }) </script> <div id="demo3"> </div> <script id="class2-template" type="text/x-handlebars-template"> {{#each this}} <dl> <dt>{{class}}</dt> {{#with student}} {{#each this}} <dd>{{this}}</dd> {{/each}} {{/with}} </dl> {{/each}} </script> <script> $(function(){ var data2 = [ { class:"一年级", student:[ "王晓飞", "陈扇", "理查德" ] }, { class:"二年级", student:[ "朱暖", "张坚庭", "刘海得" ] }] var myTemplate = Handlebars.compile($("#class2-template").html()); $("#demo3").html(myTemplate(data2)); }) </script> <body> </body> </html>
点击下载:
时间: 2024-11-01 13:42:19