handlebars.js模版引擎入门案例

时间:2021-08-28 02:09:39
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/handlebars.js/4.0.6/handlebars.js"></script>
<title>handlebars</title>
</head>
<body>

<div class="box"></div>
</body>
<!--创建一个模版,id是必须的-->
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>
{{title}}</h1>
<div class="body">
{{body}}
</div>
</
div>
</script>
<script type="text/javascript">
//获取模版里面的内容
var source = $("#entry-template").html();
//模版渲染
var template = Handlebars.compile(source);
//定义数据
var context = {title: "My New Post", body: "This is my first post!"};
var html = template(context);
//模版装载到dom节点上
$(".box").html(html);
</script>
</html>