Add a template function

This commit is contained in:
Andrea Fazzi 2024-08-08 07:00:24 +02:00
parent 1f700ca1ea
commit d2f38884d8

View file

@ -1,8 +1,19 @@
let app = document.querySelector('#app'); let app = document.querySelector('#app');
let endpoint = 'https://vanillajsacademy.com/api/dragons.json'; let endpoint = 'https://vanillajsacademy.com/api/dragons.json';
let articleTmpl = function (item) {
return `
<article>
<h2>${item.title}</h2>
<cite>${item.pubdate} by <strong>${item.author}</strong></cite>
<p>${item.article}</p>
</article>
<hr/>
`
}
async function getArticles() { async function getArticles() {
app.innerHTML = 'Fetching articles...'; app.innerHTML = 'Fetching all articles...';
try { try {
let response = await fetch(endpoint); let response = await fetch(endpoint);
@ -12,12 +23,7 @@ async function getArticles() {
if (!dragons) throw 'no data'; if (!dragons) throw 'no data';
app.innerHTML = dragons.articles.map(function(item) { app.innerHTML = dragons.articles.map(function(item) {
return ` return `${articleTmpl(item)}`;
<h2>${item.title}</h2>
<cite>${item.pubdate} by <strong>${item.author}</strong></cite>
<p>${item.article}</p>
<hr/>
`
}).join(''); }).join('');
} catch (error) { } catch (error) {