Skip to content

Instantly share code, notes, and snippets.

@pdehaan
Created April 7, 2022 23:22
Show Gist options
  • Select an option

  • Save pdehaan/d9a976ad5798fde41b08bd89d6986f8d to your computer and use it in GitHub Desktop.

Select an option

Save pdehaan/d9a976ad5798fde41b08bd89d6986f8d to your computer and use it in GitHub Desktop.
Looping and templating w/ Alpine.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<style>
h2 {
color: salmon;
font-family: "Comic Sans MS";
}
dt {
font-weight: bold;
margin-left: 1.5em;
}
</style>
</head>
<body>
<div x-data="{ breaches: [] }"
x-init="breaches = await fetchBreaches()">
<h2>Fetch test</h2>
<section>
<template x-for="breach in breaches" :key="breach.Name">
<article x-show="breach.IsSensitive === true" x-bind:data-sensitive="breach.IsSensitive">
<h3 x-text="breach.Title"></h3>
<dl>
<dt>Breach Date</dt>
<dd><time x-bind:datetime="breach.BreachDate" x-text="dateFormat(breach.BreachDate)"></time></dd>
<dt>Data Classes</dt>
<!-- <dd x-text="formatList(breach.DataClasses)"></dd> -->
<dd>
<ul>
<template x-for="dataClass in breach.DataClasses">
<li x-text="dataClass"></li>
</template></li>
</ul>
</dd>
<dt x-show="breach.Domain">Domain</dt>
<dd x-show="breach.Domain"><a x-bind:href="'http://' + breach.Domain" x-text="breach.Domain"></a></dd>
</dl>
<!-- <pre x-text="JSON.stringify(breach)"></pre> -->
</article>
</template>
</section>
</div>
<script>
async function fetchBreaches() {
const breaches = await fetch('https://haveibeenpwned.com/api/v3/breaches').then(res => res.json());
// Sort by `BreachDate`, descending.
return breaches.sort((a, b) => b.BreachDate.localeCompare(a.BreachDate));
}
function formatList(arr = [], locale="en") {
return new Intl.ListFormat(locale, { style: 'long', type: 'conjunction' }).format(arr);
}
function dateFormat(dateStr) {
// return new Date(dateStr).toLocaleDateString("en");
return new Intl.DateTimeFormat('en-US', {dateStyle: "long"}).format(new Date(dateStr));
}
</script>
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment