修复车把JS在客户端不起作用的问题



我正在尝试使用车把模板。我为我的服务器使用了快速车把,我想使用车把 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>

请帮忙。谢谢

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

尝试在 JS 中使用这一行:

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

在车把中:

{{#each this}}

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

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

然后你把对象解析为templatetemplate(Displayhtml),然后它就可以工作了!!

在前端(如果您也像在服务器端渲染中使用车把,则必须在车把中的任何帮助程序之前(:

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

最新更新