DEV Community

Cover image for How to print your API easily with Handlebars and Ajax. 🎯
Luca
Luca

Posted on

How to print your API easily with Handlebars and Ajax. 🎯

Today I want to show you how to use Handlebars for print your API from an Ajax call. πŸ‘©β€πŸ’»

First of all you need to take Handlebars script on the site:
https://handlebarsjs.com

FIRST (HTML):
1️⃣) On your head you need to add a script:

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.    3/handlebars.min.js"></script>
</head>
Enter fullscreen mode Exit fullscreen mode

2️⃣)Create your "div space" where you want to print your handlebars template

<div class="append-here>
   <-- your template append here -->
</div>
Enter fullscreen mode Exit fullscreen mode

3️⃣) On bottom of your page you need to add your template:

<head>
 <script id="template" type="text/x-handlebars-template">
      <!-- Insert here the data which you want to print with an Ajax  -->
 </script>
</head>
Enter fullscreen mode Exit fullscreen mode

SECOND STEP (JAVASCRIPT)

1️⃣) Call your API with a classic Ajax call:

var baseUrl = 'https:...';

$.ajax ({
    url: baseUrl,
    method: 'GET',
    success:function(data){
        printData(data);
    },
    error: function(){
        alert('error');
    }
})

Enter fullscreen mode Exit fullscreen mode

2️⃣) Cycle your data, determinate a object (in this case dataStamp) and the append the result into your handlebars template like this:

var source = $("#template").html();
var templateMissions = Handlebars.compile(source);

function printData(datas){
    for (var i = 0; i < datas.length; i++) {
        var data = datas[i];
        var dataStamp = {
            name: data.name,
            description: data.description,
            img: data.imageUrl
        }
        var template = template(dataStamp)
        $('.append-here').append(template);
    }
}
Enter fullscreen mode Exit fullscreen mode

Ok summing up:
❗) Source is your html template, and determinate a variable for compile your handlebars template.

var source = $("#template").html();
var template = Handlebars.compile(source);

Enter fullscreen mode Exit fullscreen mode

❗)After cycle you need to determinate which data you want to append on your template, and in which div class you want to append/see your API print.

var template = template(dataStamp)
$('.append-here').append(template);
Enter fullscreen mode Exit fullscreen mode

THIRD STEP
Append this on your HTML handlebars template with:

<script id="template" type="text/x-handlebars-template">  
<h1> {{name}} </h1>
<p> {{description}} </p>
<img src="{{image}}" style="height:100px">
</script>
Enter fullscreen mode Exit fullscreen mode

It is an easy way for print all your API result with HTML and Javascript, like a PHP method @foreach. πŸ’β€β™‚οΈ

Top comments (0)