Skip to content

Instantly share code, notes, and snippets.

@snellingio
Created January 17, 2022 18:20
Show Gist options
  • Save snellingio/92091af04db95ee91b6a4fa5e4df27b8 to your computer and use it in GitHub Desktop.
Save snellingio/92091af04db95ee91b6a4fa5e4df27b8 to your computer and use it in GitHub Desktop.
Import Alpine components
<style>
[x-show="!open"] {
color: red;
}
[x-show="open"] {
color: green;
}
</style>
<template>
<div x-data="dropdown">
<button @click="toggle">...</button>
<div x-show="!open">Closed</div>
<div x-show="open">Opened</div>
</div>
</template>
<script>
Alpine.data('dropdown', () => ({
open: false,
toggle() {
this.open = !this.open
}
}))
</script>
<html>
<head>
<style>
body{
padding: 30px;
}
</style>
</head>
<body>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<template x-data x-import="/component.html"></template>
<script>
document.addEventListener('alpine:init', () => {
Alpine.directive('import', (el, {expression}, {evaluate}) => {
fetch(expression)
.then(response => response.text())
.then(html => {
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
var script = doc.querySelector('script');
var style = doc.querySelector('style');
var template = doc.querySelector('template');
if (script !== null) {
var scriptEl = document.createElement('script');
scriptEl.innerHTML = script.innerHTML;
document.head.appendChild(scriptEl);
}
if (style !== null) {
document.head.appendChild(style);
}
if (template !== null) {
el.outerHTML = (template.content.firstElementChild.cloneNode(true)).outerHTML;
}
evaluate()
});
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment