Skip to content

Alpine.js

Anvil runs the CSP build of Alpine.js: templates can only reference properties, getters and methods of components registered with Alpine.data() by name (x-show="isOpen", @click="toggle", :class="menuClass"). Expressions in attributes are not used in Anvil’s views; inline scripts and on… attributes are blocked by the CSP.

Anvil registers its components in resources/js/components/alpine.js (anvilTheme, anvilSidebar, anvilTabs, anvilNavGroup, anvilTags, anvilRepeater, anvilMarkdown, anvilLookup, anvilWizard, anvilGlobalSearch, anvilBulk). They belong to Anvil’s views; register your own in a script of the panel:

// public/js/app.js, returned from Panel::scripts()
document.addEventListener('alpine:init', () => {
Alpine.data('ticketFilter', () => ({
open: false,
get menuClass() { return this.open ? 'show' : ''; },
toggle() { this.open = !this.open; },
}));
});
  • Pass server values in data-* attributes and read them in init() (this.$el.dataset); do not render JSON into scripts.
  • In methods use this.$root for the component element; this.$el is the element of the current event handler.
  • To add values to an htmx request of the component, listen to htmx:configRequest in init() and set event.detail.parameters, as anvilMarkdown and anvilLookup do.

See Scripts and Alpine components.