javascripttemplateshandlebars.jsclient-side-templating

fix handlebar js not working on client side


I am trying to use handlebars templates. I used Express-handlebars for my server, and i want to use handlebars js for my client side rendering.

This is the script for the handlebars template.

<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>

For the client side

  <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();
});

My response is an array with an object inside, for example:[ {title:"Black Cap", price:60}]. But nothing shows on the page!!!. the data which i am supposed to send as html displays like : :

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

Please help. Thanks


Solution

  • Handlebars js api, only accepts a javascript object. if you create an object, Displayhtml with the result array as a field, like this :

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

    Then you parse the object to the template: template(Displayhtml). then it works!!!

    In front-end(you must but a \ before any helper in handlebars if you are also using handlebars as in server-side rendering ):

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