本篇将介绍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"> {{!-- 注释: 自定义注册chinese关键字 将序号变为中文序号--}} <div>中文序号: {{chinese @index}}</div> <div>姓名 {{name}}</div> <div>年龄 {{age}}</div> <div>信息 {{info}}</div> <ul> {{#each skill}} {{!-- 注释: 把第一个技能设置为红色--}} <li {{#isfirst @index}} style="color: red;" {{/isfirst}} > {{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: "分手都发生过的环境广告", age: 30, skill:[ "听音乐", "打篮球-三分投射", ] } ]; //registerHelper是自定义标签 //高级用法之自定义注册一个chinese属性 Handlebars.registerHelper("chinese",index => { let arr = ["一","二","三"]; return arr[index]; }); //高级用法之自定义注册一个isfirst属性 Handlebars.registerHelper("isfirst",(index,options)=>{ if (index===0){ return options.fn(this); } }); //找到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的学习就告一段落了,有写的不对的地方请指正,谢谢