前端最常用的模板引擎-Handlebars

接触过的模板引擎不算多,只用过jsp和ejs,jsp属于Java语系范畴也不算难,对于大前端来说,Handlebars怎么能够缺席,前端必须掌握技能之一,模板引擎Handlebars。

Handlebars 是 JavaScript 一个语义模板库,通过对viewdata的分离来快速构建Web模板。Handlebars是全球使用率最高的模板引擎,也成为全球最受欢迎的模板引擎,Handlebars模板看起来和HTML一样,只是嵌入了handlebars表达式。

附上参考教程:https://www.jianshu.com/p/2ad73da601fc

优点:
1:使用Handlebars,可以轻松创建语义化模板;
2:可以保证模板加载和运行的速度;
3:基本语法极其简单,使用{{value}}将数据包装起来即可;
4:轻量级,兼容性好;

步骤:

1:使用<script>标签引入handlebars模板:

<!--创建一个模版,id是必须的-->
<script id="entry-template" type="text/x-handlebars-template">
    <div class="entry">
     
    </div>
</script>

2:在javascript中使用Handlebars.compile编译模板:

 //获取模版里面的内容
    var source = $("#entry-template").html();
    //模版渲染
    var template = Handlebars.compile(source);

3:看一下具体的例子:

<!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: "王小婷的空间", body: "欢迎来到王小婷的世界里"};
    var html = template(context);
    //模版装载到dom节点上
    $(".box").html(html);
</script>
</html>

5640239-f7338273ac24ffae.png

原文作者:祈澈姑娘 技术博客:https://www.jianshu.com/u/05f416aefbe1
90后前端妹子,爱编程,爱运营,爱折腾。 坚持总结工作中遇到的技术问题,坚持记录工作中所所思所见,欢迎大家一起探讨交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值