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. πββοΈ
Top comments (0)