Search code examples
javascripthandlebars.js

How to handle data from json with handlebars


I have the next problem, I need to get some information when my html load. That information comes from an api rest so I have an ajax function that do that and the html. I didn't find other way than putting the handlebars tags inside the script and then adding the div that is appended.

Is the another way?

$(document).ready(

  function obtenerProperties(){
   $.ajax({
     url: "http://127.0.0.1:9000/property?type=URL",
     success: function(data){

      var source = $("#properties-template").html();

      var template = Handlebars.compile(source);

     $(".prueba").append(template(data));

     },
      error: function(data) {
      console.log('error', data);
      }
   })
   }

 );

HTML:

     <body>
    <script id="properties-template" type="text/x-handlebars-template">
        <div class="">
            <table class="table">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col">Nombre</th>
                        <th scope="col">Tipo</th>
                        <th scope="col">Cron</th>
                    </tr>
                </thead>
                <tbody>
                        {{#each properties}}
                    <tr>

                        <th scope="row">1</th>
                        <td>{{clave}}</td>
                        <td>{{valor}}</td>
                        {{/each}}
                    </tr>
                </tbody>
            </table>
        </div>
  </script>
  <div class="prueba">
  </div>
</body>

Solution

  • Edited answer, I put the $ajax call in a separate script tab within the html body and moved the pruba class to `tbody'.

     `<body>
    <script>
    $(document).ready(
      function obtenerProperties(){
       $.ajax({
     url: "http://127.0.0.1:9000/property?type=URL",
     success: function(data){
      var source = $("#properties-template").html();
      var template = Handlebars.compile(source);
     $(".prueba").append(template(data));
     },
      error: function(data) {
      console.log('error', data);
      }
     })
    });
    </script>
    <script id="properties-template" type="text/x-handlebars-template"/>
        <div class="">
            <table class="table">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col">Nombre</th>
                        <th scope="col">Tipo</th>
                        <th scope="col">Cron</th>
                    </tr>
                </thead>
                <tbody class="prueba">
                        {{#each properties}}                   
                        {{data}}                      
                        {{/each}}                  
                </tbody>
            </table>
        </div>
    </body>`