Skip to content

Instantly share code, notes, and snippets.

@Saeven
Created June 30, 2021 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Saeven/aac6c44fc8ac8dfb3d73e6011087e121 to your computer and use it in GitHub Desktop.
Save Saeven/aac6c44fc8ac8dfb3d73e6011087e121 to your computer and use it in GitHub Desktop.
Drawing a templated list with AlpineJS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.4/tailwind.min.css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.2.1/cdn.js" defer></script>
</head>
<body>
<!-- partial:index.partial.html -->
<div x-data='sampleModel()'>
<!-- test -->
<h1 data-text x-text="items[1].title"></h1>
<div class="mt-6 relative px-4 sm:px-6">
<div class="px-4 sm:px-6 space-y-6" x-html="generateList()">
</div>
</div>
<template x-ref="template-heading">
<div class="bg-yellow-50 border-l-4 border-yellow-400 p-4">
<span>Heading</span>
<h1 data-text></h1>
</div>
</template>
<template x-ref="template-item">
<div class="bg-blue-50 border-l-4 border-blue-400 p-4">
<span>Item</span>
<h3 data-text></h3>
<p data-description></p>
</div>
</template>
</div>
<!-- partial -->
<script>
function sampleModel() {
return {
items: {
1: {type: "heading", title: "Shared Hosting Plan"},
2: {type: "item", title: "Shoes", description: "This is a test"},
3: {type: "item", title: "A Belt", description: "This is a test"}
},
generateList() {
let markup = '';
for (const id of Object.keys(this.items)) {
const templateContent = this.$refs["template-" + this.items[id].type];
const copy = templateContent.cloneNode(true);
let textNode = copy.content.querySelector('[data-text]')
textNode.setAttribute('x-text', 'items[' + id + '].title' );
markup += copy.innerHTML;
}
return markup;
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment