【问题标题】:fix handlebar js not working on client side修复车把 js 在客户端不起作用
【发布时间】:2020-02-14 14:34:09
【问题描述】:

我正在尝试使用车把模板。我在服务器上使用了 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();
});

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

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

请帮忙。谢谢

【问题讨论】:

  • 你的路由文件代码在哪里?

标签: javascript templates handlebars.js client-side-templating


【解决方案1】:

你应该确保数据结构是正确的:

在 JS 中尝试这一行:

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

在车把中:

{{#each this}}

【讨论】:

    【解决方案2】:

    Handlebars js api,只接受一个 javascript 对象。 如果您创建一个对象,Displayhtmlresult 数组作为字段,如下所示:

    Displayhtml={
       results:[ {title:"Black Cap", price:60}]
    }
    

    然后你将对象解析为template:template(Displayhtml)。然后就可以了!!!

    在前端(如果您也在服务器端渲染中使用车把,则必须在车把中的任何助手之前添加\):

    \{{# each results}}
    \\do whatever you want. 
    \{{/each}}
    

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 2016-05-02
      • 1970-01-01
      • 2019-01-26
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      相关资源
      最近更新 更多