How to print your API easily with Handlebars and Ajax. šÆ
Luca
Posted on August 19, 2020
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>
2ļøā£)Create your "div space" where you want to print your handlebars template
<div class="append-here>
<-- your template append here -->
</div>
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>
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');
}
})
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);
}
}
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);
ā)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);
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>
It is an easy way for print all your API result with HTML and Javascript, like a PHP method @foreach. šāāļø
Posted on August 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.