介绍
Handlebars 是 JavaScript 一个语义模板库,通过对view和data的分离来快速构建Web模板。它采用”Logic-less template”(无逻辑模版)的思路,在加载时被预编译,而不是到了客户端执行到代码时再去编译, 这样可以保证模板加载和运行的速度。Handlebars兼容Mustache,你可以在Handlebars中导入Mustache模板。
以下是我学习Handlebars的第一个demo。页面引入handlebars.js和jquery.js。
<!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>
页面效果: