介绍html
Handlebars 是 JavaScript 一个语义模板库,经过对view和data的分离来快速构建Web模板。它采用”Logic-less template”(无逻辑模版)的思路,在加载时被预编译,而不是到了客户端执行到代码时再去编译, 这样能够保证模板加载和运行的速度。Handlebars兼容Mustache,你能够在Handlebars中导入Mustache模板。jquery
如下是我学习Handlebars的第一个demo。页面引入handlebars.js和jquery.js。json
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>黄宝康的第一个Handlebars案例</title> <script src="handlebars.js"></script> <script src="jquery.js"></script> </head> <body> <script id="tpl" type="text/x-handlebars-template"> <div class="demo"> <h1>{{name}}</h1> <p>{{content}}</p> </div> </script> <script> var source = $("#tpl").html();// 获得模板原始内容 var template = Handlebars.compile(source);//编译以后返回类型为Function var json = {name:'黄宝康',content:'个人第一个Handlebars模板引擎demo'};//模拟数据 var html = template(json);// 函数调用以后返回填充后的数据 $('body').html(html); </script> </body> </html>
页面效果: less