### Install htmx.org via npm Source: https://putyourlightson.com/plugins/sprig/index This command shows how to install the htmx.org package using npm, allowing developers to manage htmx as a project dependency. This approach requires manual updates to keep htmx in sync with Sprig's requirements. ```Bash npm install htmx.org ``` -------------------------------- ### Install Sprig Plugin via Composer Source: https://putyourlightson.com/plugins/sprig/index This command installs the Sprig plugin for Craft CMS using Composer, the PHP dependency manager. It's the recommended way to add the plugin to your Craft project. ```Shell composer require putyourlightson/craft-sprig ``` -------------------------------- ### s-on:* Attribute Usage Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how to use the s-on:* attribute to respond to events directly on an HTML element, similar to htmx's hx-on. The example shows toggling a CSS class on click. ```HTML
Show/hide more
``` -------------------------------- ### s-trigger Attribute for Request Events Source: https://putyourlightson.com/plugins/sprig/index Shows how to use the s-trigger attribute to define the event that initiates a request. The example demonstrates triggering a request on 'keyup' with a 'changed' modifier and a 'delay'. ```HTML ``` -------------------------------- ### Composer: Require Sprig Core for Control Panel Usage Source: https://putyourlightson.com/plugins/sprig/index To enable Sprig functionality within a Craft custom plugin or module for control panel development, without requiring the full Sprig plugin installation, add `putyourlightson/craft-sprig-core` to your project's `composer.json` file. ```JSON { "require": { "putyourlightson/craft-sprig-core": "^2.0" } } ``` -------------------------------- ### s-swap Attribute for DOM Content Swapping Source: https://putyourlightson.com/plugins/sprig/index Demonstrates the s-swap attribute, which controls how the server response content is integrated into the DOM. The example shows replacing the outer HTML of a target element. ```HTML ``` -------------------------------- ### Handling Form Submissions with `s-action`, `s-method`, and Sprig Status Checks Source: https://putyourlightson.com/plugins/sprig/index This comprehensive example shows a form using `s-action` and `s-method` for a POST request, typically for updating data. It also demonstrates how to check the success or error status of the Sprig request using `sprig.isSuccess` and `sprig.isError` to display appropriate messages to the user. ```HTML
{% if sprig.isSuccess %} Product added to your cart! {% elseif sprig.isError %} Error: {{ sprig.message }} {% endif %} ``` -------------------------------- ### Access Request Parameters in Sprig Component (Twig) Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how query string and body parameters from the HTTP request are automatically accessible as variables within Sprig components, provided they do not start with an underscore. It also shows how to set a default value for such parameters. ```Twig {# The query string `?query=Wanda` is provided in the URL #} {# Sets to a default value if not defined #} {% set query = query ?? '' %} Search results for “{{ query }}” {# Outputs: Search results for “Wanda” #} ``` -------------------------------- ### s-method Attribute for HTTP Request Method Source: https://putyourlightson.com/plugins/sprig/index The `s-method` attribute explicitly sets the HTTP verb for a request. Supported values include `get` (default), `post`, or any other valid HTTP method. When set to anything other than `get`, Sprig automatically includes a CSRF token in the request for security. ```HTML
``` -------------------------------- ### Standard HTML Form for Craft Controller Action Source: https://putyourlightson.com/plugins/sprig/index An example of a traditional HTML form configured to submit data to a Craft CMS controller action, specifically for updating a cart. It includes standard `method`, `action` (hidden input), `csrfInput()`, and other form fields. ```HTML {{ csrfInput() }}
``` -------------------------------- ### Discouraged Alpine.js Runtime Data Declaration Source: https://putyourlightson.com/plugins/sprig/index This example illustrates a discouraged pattern for defining Alpine.js data using `Alpine.data` within a script block. While functional, it separates the data definition from the component's HTML, making the code less readable and maintainable compared to inline directives. ```HTML
Content...
``` -------------------------------- ### Get htmx Version (Twig) Source: https://putyourlightson.com/plugins/sprig/index Retrieves the htmx version string used by the current Sprig instance, useful for compatibility checks or debugging within Twig templates. ```Twig {{ sprig.htmxVersion }} ``` -------------------------------- ### Handling htmx Events with Twig's JS Tag Source: https://putyourlightson.com/plugins/sprig/index This example demonstrates how to attach an event listener to htmx events, specifically `htmx:afterSwap`, using Craft CMS's `{% js %}` Twig tag. This ensures the JavaScript runs after htmx has loaded and performed its DOM manipulation. ```Twig {% js %} htmx.on('htmx:afterSwap', function(event) { // do something }); {% endjs %} ``` -------------------------------- ### Registering JavaScript with Variable Escaping in Sprig Source: https://putyourlightson.com/plugins/sprig/index This example shows how to safely embed dynamic data into JavaScript code registered with Sprig, preventing XSS vulnerabilities. It uses Twig's `|escape('js')` filter to properly escape variables before they are included in the JavaScript string. ```Twig {% set js %} console.log('{{ message|escape('js') }}'); {% endset %} {% do sprig.registerJs(js) %} ``` -------------------------------- ### Initialize Sprig Load More Component (Twig) Source: https://putyourlightson.com/plugins/sprig/index The main Twig template (main.twig) snippet that initializes a _components/load-more component, passing an initial offset and a protected _limit variable to control pagination. ```Twig {#-- main.twig --#} {# Creates a component from the template path #} {{ sprig('_components/load-more', { offset: 0, _limit: 1, }) }} ``` -------------------------------- ### APIDOC: `sprig.swapOob` Function Reference Source: https://putyourlightson.com/plugins/sprig/index API reference for the `sprig.swapOob` function, used for out-of-band template swapping. ```APIDOC sprig.swapOob(target: string, templatePath: string, variables: array = null) target: CSS selector for the element to swap. templatePath: Path to the Twig template to render. variables: (Optional) An array of variables to pass to the template. ``` -------------------------------- ### Sprig Load More Component Implementation (Twig) Source: https://putyourlightson.com/plugins/sprig/index The core logic of the _components/load-more.twig component. It fetches entries using offset and _limit, displays them, and includes a Sprig-enabled button to dynamically load more entries by updating the offset and replacing the content. ```Twig {#-- _components/load-more.twig --#} {% set entries = craft.entries.offset(offset).limit(_limit).all() %} {% for entry in entries %}

{{ entry.title }}

{% endfor %} {% if entries %}
{% endif %} ``` -------------------------------- ### Composer PSR-4 Autoload Configuration for Sprig Components Source: https://putyourlightson.com/plugins/sprig/index Illustrates the `composer.json` entry required to configure PSR-4 autoloading for Sprig component classes, mapping the `sprig\components\` namespace to the `sprig/components/` directory. ```JSON "autoload": { "psr-4": { "sprig\\components\\": "sprig/components/" } }, ``` -------------------------------- ### Initialize Sprig Component in Twig Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how to initialize a Sprig component within a main Twig template using the `sprig()` function. This function takes the component's template path as its first parameter, creating a reactive partial that can be re-rendered via AJAX. ```Twig {#-- main.twig --#} {% extends '_layout' %} {% block main %} {# Creates a component from the template path #} {{ sprig('_components/search') }} {% endblock %} ``` -------------------------------- ### PHP: Bootstrap Sprig Module in Craft Plugin Source: https://putyourlightson.com/plugins/sprig/index Bootstrap the Sprig module from within your Craft plugin or module's `init` method. This step is essential to properly initialize and enable Sprig functionality for use in control panel templates. ```PHP use craft\base\Plugin; use putyourlightson\sprig\Sprig; class MyPlugin extends Plugin { public function init(): void { parent::init(); Sprig::bootstrap(); } } ``` -------------------------------- ### Set htmx Configuration Options Source: https://putyourlightson.com/plugins/sprig/index Allows setting global htmx configuration options via a meta tag. The `options` parameter is an object mapping htmx configuration keys to their desired values. ```Twig {% do sprig.setConfig({ requestClass: 'loading' }) %} ``` -------------------------------- ### APIDOC: `sprig.triggerRefreshOnLoad` Function Reference Source: https://putyourlightson.com/plugins/sprig/index API reference for the `sprig.triggerRefreshOnLoad` function, used for refreshing Sprig components on page load. ```APIDOC sprig.triggerRefreshOnLoad(selector: string = '.sprig-component') selector: (Optional) CSS selector for the Sprig components to refresh. Defaults to '.sprig-component'. ``` -------------------------------- ### s-prompt Attribute for User Confirmation Source: https://putyourlightson.com/plugins/sprig/index Shows how to use the s-prompt attribute to display a confirmation prompt to the user before submitting a request, useful for destructive actions like deletion. ```HTML ``` -------------------------------- ### Sprig Template Variables and Methods API Source: https://putyourlightson.com/plugins/sprig/index Comprehensive reference for the `sprig` object, providing access to various properties and methods within Sprig templates for interacting with htmx and current request data. ```APIDOC sprig: getHtmxVersion(): string - Returns the htmx version used by the current version of Sprig. getMessage(): string - Returns the message resulting from a request. getModelId(): string - Returns the model ID resulting from a request. getPrompt(): string - Returns the value entered by the user when prompted via s-prompt. getTarget(): string - Returns the ID of the target element. getTrigger(): string - Returns the ID of the element that triggered the request. getTriggerName(): string - Returns the name of the element that triggered the request. getUrl(): string - Returns the URL that the Sprig component was loaded from. isBoosted: boolean - Returns true if this is in response to a boosted request (hx-boost). isError: boolean - Returns whether this is an error request. isHistoryRestoreRequest: boolean - Returns true if the request is for history restoration after a miss in the local history cache a client-side redirect without reloading the page. isInclude: boolean - Returns true if the template is being rendered on initial page load (not through a Sprig request), otherwise, false. isRequest: boolean - Returns true if the template is being rendered through a Sprig request (not on initial page load), otherwise, false. isSuccess: boolean - Returns whether this is a success request. location(url: string): void - Triggers a client-side redirect without reloading the page. ``` -------------------------------- ### Instantiating a Sprig PHP Component in Twig Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how to create and render a Sprig component directly from a PHP class (`ContactForm`) within a Twig template, passing initial variables to its public properties. ```Twig {#-- main.twig --#} {# Creates a component from the ContactForm class #} {{ sprig('ContactForm', { message: 'Say hello', }) }} ``` -------------------------------- ### APIDOC: `sprig.triggerRefresh` Function Reference Source: https://putyourlightson.com/plugins/sprig/index API reference for the `sprig.triggerRefresh` function, used for refreshing Sprig components. ```APIDOC sprig.triggerRefresh(target: string, variables: array = null) target: CSS selector for the Sprig component to refresh. variables: (Optional) An array of variables to inject into the component before refreshing. ``` -------------------------------- ### APIDOC: `sprig.triggerEvents` Function Reference Source: https://putyourlightson.com/plugins/sprig/index API reference for the `sprig.triggerEvents` function, used for triggering client-side events. ```APIDOC sprig.triggerEvents(events: array|string) events: An array of event names, a comma-separated string of event names, or a JSON encoded string of key-value pairs. ``` -------------------------------- ### Recommended Alpine.js Inline Data Directive Usage Source: https://putyourlightson.com/plugins/sprig/index This code demonstrates the recommended way to define Alpine.js component data and methods directly within the HTML using the `x-data` directive. This approach promotes cleaner, more localized component logic. ```HTML
Content...
``` -------------------------------- ### Fetch Multiple Entries in Sprig Component (Twig) Source: https://putyourlightson.com/plugins/sprig/index Details the internal logic of a Sprig component template (_components/entries.twig) for retrieving multiple Craft CMS entries based on an array of entryIds passed from the parent template. ```Twig {% set entries = craft.entries.id(entryIds).all() %} ``` -------------------------------- ### Pass Variables to Sprig Component (Twig) Source: https://putyourlightson.com/plugins/sprig/index Demonstrates the fundamental method of creating a Sprig component and making variables available within its template by passing an object as the second parameter to the sprig function. ```Twig {{ sprig('_components/search', { query: 'Wally', }) }} ``` -------------------------------- ### Basic Sprig Component Template (Non-Reactive) Source: https://putyourlightson.com/plugins/sprig/index Shows a basic Twig template for a Sprig component, containing a simple HTML form with a text input and a submit button. In this initial state, the component is not yet reactive and requires a full page reload for any updates. ```Twig {#-- _components/search.twig --#}
``` -------------------------------- ### s-replace Attribute for Content Replacement Source: https://putyourlightson.com/plugins/sprig/index Explains how the s-replace attribute specifies which element to replace in the DOM. It demonstrates a shorthand for combining s-select, s-target, and s-swap to replace a specific element with content from the server response. ```HTML ``` ```HTML {# Equivalent to: #} ``` -------------------------------- ### s-val:* Attribute for Dynamic Values Source: https://putyourlightson.com/plugins/sprig/index Explains the s-val:* attribute, which provides a readable way to populate the s-vals attribute with dynamic values. It shows how to pass page and limit parameters, and how kebab-case attributes are converted to camelCase in Twig templates. ```Twig ``` ```Twig {# Equivalent to: #} ``` ```Twig {% set myCustomPage = myCustomPage ?? '' %} ``` -------------------------------- ### s-boost Attribute for AJAX Boosting Source: https://putyourlightson.com/plugins/sprig/index The `s-boost` attribute enhances standard HTML anchors and form tags to utilize AJAX for requests, providing a smoother user experience without full page reloads. It integrates with htmx's boosting capabilities. -------------------------------- ### Register JavaScript Code for Execution Source: https://putyourlightson.com/plugins/sprig/index Registers a given JavaScript string to be executed in the current request context. It intelligently handles registration for includes or full requests, ensuring the script runs correctly. ```Twig {# Single line usage #} {% do sprig.registerJs('console.log("hello")') %} {# Multi-line usage #} {% set js %} console.log('hello, {{ name }}') {% endset %} {% do sprig.registerJs(js) %} ``` -------------------------------- ### Sprig Live Search Input with Dynamic Results Source: https://putyourlightson.com/plugins/sprig/index This snippet creates a live search input field that updates a dedicated results area. The `s-trigger` attribute listens for user input with a delay, and `s-target` ensures only the inner HTML of the `#results` div is replaced. The Twig code queries Craft CMS entries based on the input and displays their titles. ```Twig {# Sets to a default value if not defined #} {% set query = query ?? '' %}
{% if query %} {% set entries = craft.entries() .search(query) .orderBy('score') .all() %} {% for entry in entries %} {{ entry.title }} {% endfor %} {% endif %}
``` -------------------------------- ### Sprig PHP Component with Template, Properties, and Action Method Source: https://putyourlightson.com/plugins/sprig/index Expands the `ContactForm` component by setting a default template path, defining public properties that become available in the template, and including a `send` public method callable as an action. ```PHP success = SomeEmailApi::send([ 'email' => $this->email, 'message' => $this->message, ]); if (!$this->success) { $this->error = SomeEmailApi::getError(); } } } ``` -------------------------------- ### Paginate Query Results and Access Page Info Source: https://putyourlightson.com/plugins/sprig/index The `sprig.paginate` method processes an element or active query, returning a `pageInfo` variable. This variable provides details about the current page's results, total elements, page numbers, and utility methods for generating page ranges. It extends Craft's Paginate variable. ```APIDOC sprig.paginate(query: ElementQuery|ActiveQuery, page: int = 1) -> pageInfo pageInfo: pageResults: array // The element results for the current page. first: int // The offset of the first element on the current page. last: int // The offset of the last element on the current page. total: int // The total number of elements across all pages. currentPage: int // The current page number. totalPages: int // The total number of pages. getRange(start: int, end: int): array // Returns a range of page numbers as an array. getDynamicRange(max: int): array // Returns a dynamic range of page numbers that surround (and include) the current page as an array. ``` ```Twig {% set query = craft.entries.limit(10) %} {% set pageInfo = sprig.paginate(query, page) %} {% set entries = pageInfo.pageResults %} Showing {{ pageInfo.first }} to {{ pageInfo.last }} of {{ pageInfo.total }} entries. Showing page {{ pageInfo.currentPage }} of {{ pageInfo.totalPages }}. ``` -------------------------------- ### Dynamically Update Parameters with s-val:* (HTML/Twig) Source: https://putyourlightson.com/plugins/sprig/index Presents a more readable and convenient alternative to s-vals. The s-val:* attribute allows specifying individual parameters directly, where * is the parameter name (kebab-case converted to camelCase), simplifying dynamic parameter updates. ```HTML ``` -------------------------------- ### Define Sprig Component with Custom Attributes Source: https://putyourlightson.com/plugins/sprig/index Illustrates how to create a Sprig component using the `sprig()` function, passing a hash of custom attributes in the third parameter. Attributes prefixed with `s-` apply logic directly to the component element, such as `s-trigger` for defining refresh events. ```Twig {{ sprig('_components/search', {}, { 'id': 'search-component', 's-trigger': 'load, refresh', }) }} ``` -------------------------------- ### Fetch Single Entry in Sprig Component (Twig) Source: https://putyourlightson.com/plugins/sprig/index Shows the internal logic of a Sprig component template (_components/entry.twig) for retrieving a single Craft CMS entry using the entryId variable passed from the parent template. ```Twig {% set entry = craft.entries.id(entryId).one() %} ``` -------------------------------- ### Loading External JavaScript Files with Defer in Sprig Source: https://putyourlightson.com/plugins/sprig/index This snippet shows how to include an external JavaScript file using the `{% js %}` Twig tag, with the `defer: true` option. Deferring script loading ensures that htmx is fully loaded before the external script executes, preventing potential conflicts. ```Twig {% js '/assets/js/script.js' with { defer: true } %} ``` -------------------------------- ### Handle Input Variables and Display Search Results in Sprig Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how to access input field values as template variables (e.g., `query`) within a Sprig component. It also shows how to set a default fallback value for variables using the null coalescing operator and conditionally display search results by querying Craft CMS entries. ```Twig {# Sets to a default value if not defined #} {% set query = query ?? '' %}
{# Outputs the result if `query` is not empty #} {% if query %} {% set entries = craft.entries() .search(query) .orderBy('score') .all() %} {% for entry in entries %} {{ entry.title }} {% endfor %} {% endif %}
``` -------------------------------- ### Trigger Client-Side Redirect (Twig) Source: https://putyourlightson.com/plugins/sprig/index Executes a client-side redirect to a new URL without causing a full page reload, leveraging htmx's `hx-location` functionality for seamless navigation. ```Twig {% do sprig.location('/page' ~ page) %} ``` -------------------------------- ### Basic Sprig PHP Component Class Definition Source: https://putyourlightson.com/plugins/sprig/index Defines a foundational PHP class `ContactForm` that extends `putyourlightson\sprig\base\Component`, serving as the base structure for a custom Sprig component. ```PHP
{% endif %} {% if query %} {% set entries = craft.entries() .search(query) .orderBy('score') .all() %} {% for entry in entries %} {{ entry.title }} {% endfor %} {% endif %} ``` -------------------------------- ### Add Parameters with s-vals Attribute (HTML/Twig) Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how to add parameters to a request using the `s-vals` attribute. The value must be a JSON-encoded list of name-value pairs, suitable for passing dynamic data to the server. ```HTML ``` -------------------------------- ### Registering Basic JavaScript with Sprig Source: https://putyourlightson.com/plugins/sprig/index This snippet demonstrates the simplest way to execute inline JavaScript code within a Sprig component using the `sprig.registerJs` Twig function. It's suitable for small, self-contained JavaScript commands. ```Twig {% do sprig.registerJs('console.log("hello")') %} ``` -------------------------------- ### Twig Manual htmx Script Loading Configuration Source: https://putyourlightson.com/plugins/sprig/index This Twig snippet demonstrates how to disable Sprig's automatic htmx script loading and manually include the htmx.min.js file from a specified path or CDN. This is useful for developers who prefer to host the htmx library themselves or use a different CDN. ```Twig {# Disable automatic registering and loading of the htmx script. #} {% do sprig.setRegisterScript(false) %} {# Load the required file manually from a specific path or CDN. #} ``` -------------------------------- ### Pass Entry IDs to Sprig Components (Twig) Source: https://putyourlightson.com/plugins/sprig/index Illustrates the recommended approach for passing references to Craft CMS elements (like entries) into Sprig components. Instead of passing full objects, their IDs (single or array) are used, adhering to the primitive data type limitation. ```Twig {{ sprig('_components/entry', { entryId: 1, }) }} ``` ```Twig {{ sprig('_components/entries', { entryIds: [1, 2, 3], }) }} ``` -------------------------------- ### Control Automatic htmx Script Registration Source: https://putyourlightson.com/plugins/sprig/index Configures whether Sprig should automatically register and load the htmx script when a component is created. The `value` can be a boolean (defaulting to `true`) or an array of options for `yii\web\View::registerJsFile()`. ```Twig {# Disables automatically loading the htmx script. #} {% do sprig.setRegisterScript(false) %} {# Loads the htmx script at the beginning of the document body. #} {% do sprig.setRegisterScript({ position: constant('craft\web\View::POS_BEGIN') }) %} ``` -------------------------------- ### Sprig: Swap Out-of-Band (OOB) with `swapOob` Source: https://putyourlightson.com/plugins/sprig/index Swaps a template out-of-band for a Sprig component or any target element matching a CSS selector. The `variables` parameter is an optional array to pass into the template. This function mitigates cyclical requests by preventing multiple swaps of unique components within the same request. ```Twig {% do sprig.swapOob('#myComponent', 'path/to/template') %} {% do sprig.swapOob('#myComponent', 'path/to/template', { query: query }) %} ``` -------------------------------- ### Force Browser Redirect Source: https://putyourlightson.com/plugins/sprig/index Forces the client's browser to navigate to the specified URL. This is a full page redirect, similar to an HTTP 302 redirect. ```Twig {% do sprig.redirect('/new/page') %} ``` -------------------------------- ### s-ext Attribute for Htmx Extension Enabling Source: https://putyourlightson.com/plugins/sprig/index The `s-ext` attribute enables a specific htmx extension for the element it's applied to, as well as all of its child elements. This allows for modular addition of htmx functionalities. -------------------------------- ### Trigger Sprig Re-render on Keyup Event Source: https://putyourlightson.com/plugins/sprig/index Explains how to use the `s-trigger` attribute to change the re-render event from the default `change` to `keyup`. This allows for more immediate reactivity, as the component will re-render as the user types. ```HTML ``` -------------------------------- ### Persisting Alpine.js State with the Persist Plugin Source: https://putyourlightson.com/plugins/sprig/index This snippet demonstrates how to use Alpine.js's Persist plugin to maintain component state across page loads and component re-renders. The `$persist` magic property ensures that the `count` variable's value is saved and restored automatically. ```HTML
``` -------------------------------- ### Sprig-Enhanced Form for Controller Actions Source: https://putyourlightson.com/plugins/sprig/index Transforms a standard HTML form into a reactive Sprig component by adding the `sprig` attribute and using `s-method` and `s-action` attributes. Sprig automatically handles CSRF tokens for POST requests, simplifying the form structure. ```HTML
``` -------------------------------- ### Manually Register and Load htmx Script Source: https://putyourlightson.com/plugins/sprig/index Registers and loads the htmx script. This method is typically used when automatic script registration is disabled (`sprig.setRegisterScript(false)`) or when htmx needs to be explicitly loaded on a page regardless of Sprig component presence. ```Twig {% do sprig.registerScript %} ``` -------------------------------- ### Sprig: Trigger Client-Side Events with `triggerEvents` Source: https://putyourlightson.com/plugins/sprig/index Triggers one or more client-side events. The `events` parameter can be provided as an array of event names, a comma-separated string of event names, or a JSON encoded string of key-value pairs for more complex event data. ```Twig {% do sprig.triggerEvents(['eventA', 'eventB']) %} {% do sprig.triggerEvents('eventA, eventB') %} {% do sprig.triggerEvents('{"eventA":"Value A","eventB":"Value B"}') %} ``` -------------------------------- ### Display Detailed Errors from Sprig Controller Actions Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how to iterate and display specific error messages returned by a controller action when the response includes an `errors` array. This provides more granular feedback than the general `sprig.message`. ```Twig {% if sprig.isError %} {% if errors is defined %} {% for error in errors %}

{{ error|first }}

{% endfor %} {% endif %} {% endif %} ``` -------------------------------- ### s-listen Attribute for Component Refresh Triggering Source: https://putyourlightson.com/plugins/sprig/index The `s-listen` attribute allows an element to refresh automatically when one or more specified components are refreshed. Components are identified by CSS selectors. This attribute is commonly used with the `sprig` function's third parameter to create reactive component interactions. ```Twig {{ sprig('_components/products', {}, {'id': 'products'}) }} {# This component is refreshed each time the `#product` component is refreshed. #} {{ sprig('_components/cart', {}, {'s-listen': '#products'}) }} {# Equivalent to: #} {{ sprig('_components/cart', {}, {'s-trigger': 'htmx:afterOnLoad from:#products'}) }} ``` -------------------------------- ### Force Browser Page Refresh Source: https://putyourlightson.com/plugins/sprig/index Instructs the browser to perform a full refresh of the current page. This can be used to ensure the latest content is displayed. ```Twig {% do sprig.refresh() %} ``` -------------------------------- ### s-cache Attribute for Local Caching Source: https://putyourlightson.com/plugins/sprig/index The `s-cache` attribute allows developers to control local browser caching for requests. It can specify a duration in seconds for which a request's response should be cached. If no duration is provided, it defaults to 300 seconds. ```HTML
Show details
Show details
``` -------------------------------- ### Create Sprig Component with Protected Variable (Twig) Source: https://putyourlightson.com/plugins/sprig/index Explains how to pass a variable to a Sprig component that is protected from user tampering. By prefixing the variable name with an underscore, Sprig hashes its value, ensuring its integrity. ```Twig {{ sprig('_components/search', { _section: 'news', }) }} ``` -------------------------------- ### Using `s-action` Attribute for Sprig Form Submission Source: https://putyourlightson.com/plugins/sprig/index This snippet demonstrates the `s-action` attribute on a form element, which directs the form submission to a specific controller action. This is a core Sprig mechanism for interacting with backend logic. ```HTML
``` -------------------------------- ### Twig/HTML XSS Prevention: Quoting Attributes and JavaScript Escaping Source: https://putyourlightson.com/plugins/sprig/index This snippet illustrates best practices for preventing Cross-Site Scripting (XSS) vulnerabilities in Twig templates. It shows the importance of quoting HTML attribute values and demonstrates how to use the `escape('js')` filter to safely output variables within JavaScript blocks. ```Twig {# It is unsafe to omit quotes, do NOT do this! #}
{# It is safe to use either double or single quotes. #}
{% js %} {# Escape for JavaScript. #} console.log('{{ name|escape('js') }}'); {% endjs %} ``` -------------------------------- ### Make Input Field Reactive on Change Event Source: https://putyourlightson.com/plugins/sprig/index Shows how to make a single input field reactive by adding the `sprig` attribute directly to it. With this attribute, the component will automatically re-render itself whenever the input's `change` event is triggered, typically on blur or pressing Enter. ```HTML ``` -------------------------------- ### Add Parameters with s-vars Attribute (HTML/Twig) - Deprecated Source: https://putyourlightson.com/plugins/sprig/index Shows how to add parameters using the `s-vars` attribute. This attribute is deprecated due to security concerns (Cross-Site Scripting - XSS vulnerability) as expressions are dynamically computed. It is recommended to use `s-vals` or `s-val:*` instead. ```HTML ``` -------------------------------- ### HTML Structure for Displaying HTTP Errors Source: https://putyourlightson.com/plugins/sprig/index This simple HTML snippet defines a `div` element intended to display error messages. It is initially hidden and can be toggled visible when an HTTP error occurs, providing a user-friendly feedback mechanism. ```HTML ``` -------------------------------- ### Twig Template for Sprig Contact Form Component Source: https://putyourlightson.com/plugins/sprig/index Provides the Twig template (`_components/contact-form`) that renders the contact form. It conditionally displays success/error messages and uses `sprig` and `s-action="send"` to link the form submission to the `send` method in the PHP component. ```Twig {#-- _components/contact-form --#} {% if success %} Thank you for getting in touch! {% else %} {% if error %}

{{ error }}

{% endif %} {% endif %} ``` -------------------------------- ### s-indicator Attribute for Request Indicator Source: https://putyourlightson.com/plugins/sprig/index The `s-indicator` attribute specifies which element should receive the `htmx-request` class during a Sprig request. This class is typically used to display loading indicators or other visual cues to the user while an AJAX operation is in progress. -------------------------------- ### Check for Sprig Success Status (Twig) Source: https://putyourlightson.com/plugins/sprig/index Verifies if the current Sprig request was successful and displays the corresponding message, often used for positive user feedback or success notifications. ```Twig {% if sprig.isSuccess %}

{{ sprig.message }}

{% endif %} ``` -------------------------------- ### HTML Element with Custom Mouseenter Trigger Source: https://putyourlightson.com/plugins/sprig/index Demonstrates how to use the `s-trigger` attribute to specify a custom event (mouseenter) for re-rendering a Sprig component, overriding the default trigger behavior. ```HTML
Mouse over me to re-render the component.
``` -------------------------------- ### Twig Section Validation for Security Source: https://putyourlightson.com/plugins/sprig/index This Twig snippet demonstrates how to validate user-provided 'section' variables against a predefined list of allowed sections to prevent unauthorized access to sensitive data. It ensures that only 'articles' or 'plugins' sections can be queried, mitigating risks like accessing 'secrets'. ```Twig {% set section = section ?? '' %} {% set allowedSections = ['articles', 'plugins'] %} {% if section not in allowedSections %} This section is not allowed. {% else %} {% set entries = craft.entries.section(section).all() %} %} ``` -------------------------------- ### s-target Attribute for Element Targeting Source: https://putyourlightson.com/plugins/sprig/index Illustrates the s-target attribute, used to specify the exact element in the DOM that will be affected by a server response. This is crucial for precise content updates. ```HTML ``` -------------------------------- ### Check if Template is Initial Page Load (Twig) Source: https://putyourlightson.com/plugins/sprig/index Determines if the current template rendering is occurring during the initial page load or as a result of a subsequent Sprig AJAX request, allowing for conditional rendering. ```Twig {% if sprig.isInclude %} Template rendered on initial page load {% else %} Template rendered through a Sprig request {% endif %} ``` -------------------------------- ### s-confirm Attribute for User Confirmation Source: https://putyourlightson.com/plugins/sprig/index The `s-confirm` attribute triggers a JavaScript `confirm()` dialog before a request is issued. This is useful for actions that require user verification, such as deleting an entry, preventing accidental operations. ```HTML ``` -------------------------------- ### s-history-elt Attribute for History Element Specification Source: https://putyourlightson.com/plugins/sprig/index The `s-history-elt` attribute designates a specific element that will be used for snapshotting and restoring page state during navigation. This allows for precise control over what content is preserved in the browser's history. -------------------------------- ### Display Sprig Controller Action Messages Source: https://putyourlightson.com/plugins/sprig/index Extends a Sprig-enhanced form to display feedback messages after a controller action submission. It uses `sprig.isSuccess` and `sprig.isError` to check the action's outcome and `sprig.message` to output the corresponding message. ```HTML
{% if sprig.isSuccess %}

{{ sprig.message }}

{% elseif sprig.isError %}

{{ sprig.message }}

{% endif %} ``` -------------------------------- ### HTML Element with Once Trigger Modifier Source: https://putyourlightson.com/plugins/sprig/index Shows how to apply the `once` modifier to an `s-trigger` attribute, ensuring the component re-renders only on the first occurrence of the specified event (mouseenter). ```HTML
Mouse over me to re-render the component only once.
``` -------------------------------- ### Trigger Sprig Component Refresh Programmatically Source: https://putyourlightson.com/plugins/sprig/index Shows two methods to programmatically refresh a Sprig component: using Twig's `sprig.triggerRefresh` function and via JavaScript by triggering an HTMX event on the component's element. ```Twig {% do sprig.triggerRefresh('#search-component') %} ``` ```JavaScript htmx.trigger('#search-component', 'refresh'); ``` -------------------------------- ### s-history Attribute for History State Management Source: https://putyourlightson.com/plugins/sprig/index The `s-history` attribute helps manage browser history by preventing sensitive data from being saved to `localStorage` when a snapshot of the page state is taken. This is crucial for privacy and security. -------------------------------- ### Push URL to Browser History Source: https://putyourlightson.com/plugins/sprig/index This method adds a new entry to the browser's history and updates the URL bar without a full page reload. It's useful for maintaining state during AJAX interactions. ```Twig {% do sprig.pushUrl('?page=' ~ page) %} ```