本文将介绍Handlerbars的 循环语句,判断语句等使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .content-child { float: left; background-color: silver; width: 400px; height: 200px; margin: 10px 20px; } </style> </head> <body> <div id="content"></div> <script type="text/javascript" src="../conment/jquery-1.12.3.js"></script> <script type="text/javascript" src="handlebars-v4.0.11.js"></script> <script type="text/html" id="user-template"> {{#each this}} <div class="content-child"> <div>序号: {{@index}}</div> <div>姓名 {{name}}</div> {{!-- 注释: 如果age存在 就生成--}} {{#if age}} <div>年龄 {{age}}</div> {{/if}} <div>信息 {{info}}</div> <ul> {{#each skill}} <li>{{this}}</li> {{/each}} </ul> </div> {{/each}} </script> <script type="text/javascript"> //模拟的数据 let users = [ { name: "科比", age: 39, info: "你四点就好似发动机是否抗静电", skill:[ "拍电影", "打篮球-扣篮技术", "拳击" ] }, { name: "詹姆斯", age: 36, info: "个梵蒂冈梵蒂冈分工和规范", skill:[ "拍MV", "打篮球-后仰跳投", "跳高与跳远" ] }, { name: "库里", info: "分手都发生过的环境广告", skill:[ "听音乐", "打篮球-三分投射", ] } ]; //找到user-template的模板 let $userTemplate = $("#user-template").html(); //返回的是一个函数 let fun = Handlebars.compile($userTemplate); //调用生成的fun函数 返回一个html文本 let userHtml = fun(users); //填充到html中 $("#content").html(userHtml); </script> </body> </html>下一篇介绍Handlerbars使用的高级篇
registerHelper自定义标签