I want to add data that's stored in XML Files
to the HTML View with handlebars.js
but,
Instead of make a GET of 1 url ex:http://json.org/example.html
i will want to add multiple XML Files
. I will aprreciate any help on this
Thanks in advance!
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/pets-data.json');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
Handlebars.registerHelper("calculateAge", function(birthYear) {
var age = new Date().getFullYear() - birthYear;
if (age > 0) {
return age + " years old";
} else {
return "Less than a year old";
}
});
function createHTML(petsData) {
var rawTemplate = document.getElementById("petsTemplate").innerHTML;
var compiledTemplate = Handlebars.compile(rawTemplate);
var ourGeneratedHTML = compiledTemplate(petsData);
var petsContainer = document.getElementById("pets-container");
petsContainer.innerHTML = ourGeneratedHTML;
}
<div class="page-wrap">
<h1>Handlebars js</h1>
<div id="pets-container"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script id="petsTemplate" type="text/x-handlebars-template">
{{#each pets}}
<div class="pet">
<div class="photo-column">
<img src="{{photo}}">
</div>
<div class="info-column">
<h2>{{name}} <span class="species">({{species}})</span></h2>
<p>Age: {{calculateAge birthYear}}</p>
{{#if favFoods}}
<h4 class="headline-bar">Favorite Foods</h4>
<ul class="favorite-foods">
{{#each favFoods}}
<li>{{{this}}}</li>
{{/each}}
</ul>
{{/if}}
</div>
</div>
{{/each}}
</script>