前端模板引擎-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>

原文作者:祈澈姑娘

猜你喜欢

转载自blog.csdn.net/weixin_44763569/article/details/89680089
今日推荐