首页 > 解决方案 > 修复车把 js 在客户端不起作用

问题描述

我正在尝试使用车把模板。我将 Express-handlebars 用于我的服务器,并且我想将 handlebars js 用于我的客户端渲染。

这是车把模板的脚本。

<script id="some-template" type="text/x-handlebars-template">
  <div class="row">
    {{#each result}}
    <!-- product -->
    <div class="col-md-4 col-xs-6">
      <a href="/product/{{_id}}"> <div class="product">
        <div class="product-img">
          <img src="\{{picture}}" style="height:160px;">
          <div class="product-label">
            {{#if percent}}
            <span class="sale">{{percent}}%</span>
            {{/if}}
            <span class="new">NEW</span>
          </div>
        </div>
        <div class="product-body">
          <p class="product-category">{{category}}</p>
          <h3 class="product-name"><a href="/product/{{this._id}}">{{this.title}}</a></h3>
          <h4 class="product-price">${{this.price}} <del class="product-old-price">${{this.discounted_price}}</del></h4>
          {{#if this.averagerating}}

          </div></a>

    </div>
{{/each}}
</div>
</script>

对于客户端

  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.4.2/handlebars.js" integrity="sha256-hSzapznWRy/aOZkctlN03an9DxCLlN8ZCQS0lxntiHg=" crossorigin="anonymous"></script>

$('#mybutton').click(function(){
  var post_url = $('#myform').attr("action");
  var form_data = $('#myform').serialize();
  // console.log(post_url, form_data);
  var source = $("#some-template").html();
  var template = Handlebars.compile(source);
  $('#loader').show();
  $.get( post_url, form_data, function( response ) {
    $("#searchresult").html("");
    console.log(response);
    var data = template({result:response});
    console.log(data);
    $("#searchresult").html(data);

    //$('#loader').hide();
});

Myresponse是一个数组,里面有一个对象,例如:[ {title:"Black Cap", price:60}]. 但是页面上什么都没有显示!!!我应该作为 html 发送的data显示如下:

<div class="row">
</div>

请帮忙。谢谢

标签: javascripttemplateshandlebars.jsclient-side-templating

解决方案


您应该确保数据结构正确:

尝试在 JS 中使用这一行:

...
var data = template(response);
...

在车把中:

{{#each this}}

推荐阅读