• JS模板引擎handlebars.js的简单使用


    handlebars.js的使用

    首先我们要明白handlebars.js是干什么用的,我们知道使用jsp很麻烦,

    于是我们开始使用freemarker等模板引擎,但这个只是针对服务器端来解

    析的,那么有没有一种模板引擎可以在前端实现呢,

    这个当然有,就是我们现在要了解的handlebars。

    在什么情况下使用handlebars

        答: 针对前端开发,比如做ajax的时候,原来我们使用JQuery的load方法加载页面,

        现在我们只需要有json数据过来就行了,这样减少了服务端的鸭梨,哈哈。

        或者是你在做一些界面上的应用,总之将计算交到客户端这是非常可取的方式。

    github地址:https://github.com/wycats/handlebars.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    <!DOCTYPE html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="handlebars.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <title>handlebars.js 模板引擎学习 by 雨林博客</title>
    </head>
     
    <body>
    <div id="content">
    摸板引擎测试 by 雨林博客
    </div>
    <br/>
    标题: <input id="title" /><br/>
    内容: <input id="body" /><br/>
    <button onclick="show();">显示模板内容</button>
     
     
    <!-- 模板数据 -->
    <script id="content-template" type="text/x-handlebars-template">
    <div>
      <h1>{{title}}</h1>
      <div>
        {{body}}
      </div>
    </div>
    </script>
     
    <script type="text/javascript">
    function show(){
        var source   = $("#content-template").html();//获取模板内容
        var template = Handlebars.compile(source);//返回模板编译对象,接下来可以传递参数
        //编写模板中要绑定的json数据,属性对应着模板中的变量
        var context = {title: $("#title").val(), body: $("#body").val()};
        var html    = template(context);
        $("#content").html(html);
    }
     
    </script>
    </body>
    </html>

    执行效果:

     来源:http://www.yl-blog.com/index.php/js/85.html

  • 相关阅读:
    济南空中课堂视频下载辅助脚本
    npm 修改仓库源
    Java后端实现登陆的方式
    java 新词汇
    数据库系统,设计、实现与管理(基础篇)阅读笔记
    java 面试01
    js rem 适配多端
    了解Java
    linux 查看内存使用情况
    linux 日志查看
  • 原文地址:https://www.cnblogs.com/fogwang/p/3513665.html
Copyright © 2020-2023  润新知