Handlebars 通过JavaScript对view和data的分离来快速构建Web模板

说明:

Handlebars 是 JavaScript 一个语义模板库,通过对view和data的分离来快速构建Web模板。它采用"Logic-less template"(无逻辑模版)的思路,在加载时被预编译,而不是到了客户端执行到代码时再去编译, 这样可以保证模板加载和运行的速度。Handlebars兼容Mustache,你可以在Handlebars中导入Mustache模板。

官网:

http://handlebarsjs.com/

自己的代码:

采用leancloud技术请求数据

// 界面显示的数组
var context = {
  products: []
};

// 请求列表数据
function setupData() {
  // LeanCloud - 查询
  var query = new AV.Query('Course');
  query.descending('createdAt');
  query.find().then(function (products) {
    products.forEach(function(product) {
      var id = product.id;
      var title = product.get('title');
      var description = product.get('description');
      var type = product.get('type');
      // handlebars 数组展示的context
      context.products.push({
        id,
        title,
        description,
        type,
      });
    });

    // 使用 handlebars 框架来更新 html
    var source = $("#products-list").html();
    var template = Handlebars.compile(source);
    var html = template(context);
    $('#products-detail').html(html);

  }).catch(function(error) {
    alert(JSON.stringify(error));
  });
};

// function logout() {
//   AV.User.logOut();
//   window.location.href = "./../login/login.html";
// };

//加载页面时候加载
$(function() {
  //if (isCurrentUser()) {
    setupData();
  //} else {
  //  window.location.href = "./../login/login.html";
  //}
});

//跳转新页面
function goToNewWeb(type, id) {
  if(type == "url") {
    window.open('detail-url.html#' + id,'_blank')
  }
  if(type == "article") {
    window.open('detail-article.html#' + id,'_blank')
  }
}

html

<!-- body -->
                <section class="panel panel-info portlet-item m-t">
                  <header class="panel-heading">
                    型宠 - 修剪教程 - 列表
                  </header>
                  <div class="row wrapper" id="products-detail">
                    <!-- Products list content use Handlebars -->
                    <script id="products-list" type="text/x-handlebars-template">
                      {{#each products}}
                      <div class="col-sm-6 col-md-4 product-detail" οnclick="goToNewWeb('{{{type}}}','{{{id}}}')">
                        <div class="thumbnail">
                          <div class="caption">
                            <h3>{{{title}}}</h3>
                            <p>{{{description}}}</p>
                            <p>{{{type}}}</p>
                          </div>
                        </div>
                      </div>
                      {{/each}}
                    </script>
                  </div>
                </section>
                <!-- /.body -->



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Beluga_白鲸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值