To see working examples and video tutorials, visit the Learning Resources.
Sprig attribute autocomplete support is available in IDEs via the JetBrains plugin and Visual Studio Code extension.
Sprig is a free plugin for Craft CMS that allows you to create reactive components from Twig templates and/or PHP classes. These components can re-render themselves on user-triggered events (clicks, changes to input fields, form submissions, etc.) using AJAX requests, without requiring you to write a single line of JavaScript.
Sprig enables common use-cases while completely avoiding full page refreshes:
- Live search
- Load more elements (with a button interaction or infinite scroll)
- Paginate, order and filter elements
- Add products to a cart
- Submit forms
License #
This plugin is licensed for free under the MIT License.
Requirements #
This plugin requires Craft CMS 3.1.19 or later, or 4.0.0 or later.
Installation #
To install the plugin, search for “Sprig” in the Craft Plugin Store, or install manually using composer.
composer require putyourlightson/craft-sprig
Usage #
How it Works #
Sprig components are reactive Twig templates that are used like template partials. Unlike an included template, however, a Sprig component does not automatically inherit variables from its parent context.
A single component should encapsulate related reactive behaviour and it must be able to exist independently of its parent template and the web request, since a component can be re-rendered using an AJAX request at any time.
We initialise a component using the sprig()
function, passing in a template path as the first parameter. We need to load the htmx library for Sprig to work, which can be done using the sprig.script
tag. If you prefer to host the JavaScript file in a specific location, or use a CDN, then you can load htmx.min.js using a regular script
tag. This tag should ideally be placed inside of a layout template so that it will be included in every page of the site that requires it.
{#-- _layout.twig --#}
{% block main %}{% endblock %}
{# Loads the required script #}
{{ sprig.script }}
{# Alternatively, load the required file manually from a specific path or CDN #}
<script src="/path/to/htmx.min.js" defer></script>
{#-- main.twig --#}
{% extends '_layout' %}
{% block main %}
{# Creates a component from the template path #}
{{ sprig('_components/search') }}
{% endblock %}
Inside our component template we’ll create a search form and results page (similar to the one provided in this knowledge base).
{#-- _components/search.twig --#}
<form>
<input type="text" name="query" value="">
<input type="submit" value="Search">
</form>
To make the component reactive, we simply add the sprig
attribute to any elements that should trigger a re-render.
{# The `sprig` attribute makes the form re-render the component on submit #}
<form sprig>
<input type="text" name="query" value="">
<input type="submit" value="Search">
</form>
Now each time the form
is submitted, the component will re-render itself. This happens in the background using an AJAX request to the server.
The values of all
input
fields (includingtextarea
andselect
fields) in the component will automatically become available as template variables.
This means that a variable called query
will be available, set to the value of the input field, whenever the component is re-rendered. To ensure that the query
variable is always available (including before a re-render), it is good practice to set it to a fallback default value. This is not required but generally makes components more readable.
{# Sets to a default value if not defined #}
{% set query = query ?? '' %}
<form sprig>
<input type="text" name="query" value="{{ query }}">
<input type="submit" value="Search">
</form>
<div id="results">
{# 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 %}
</div>
No full-page requests were harmed in the making of this. View the live demo.
We can make the search input field reactive and get rid of the form and search button completely, if we want to, by adding the sprig
attribute to the search field. The component will now re-render itself every time the change
event of the search input field is triggered (the default trigger for input
fields).
<input sprig type="text" name="query" value="{{ query }}">
We can also make it so that the re-render is triggered on keyup
events using the s‑trigger attribute.
<input sprig s-trigger="keyup" type="text" name="query" value="{{ query }}">
The s-trigger
attribute also provides us with event modifiers. We’ll use these to only trigger a re-render provided the field value has changed, adding a delay of 300 milliseconds (the amount of time that must pass before issuing a request). A sensible delay (also known as “debounce”) helps to prevent the server from being unnecessarily flooded with AJAX requests.
<input sprig s-trigger="keyup changed delay:300ms" type="text" name="query" value="{{ query }}">
Since we only really want to replace the search results (and not the search input field), we can target a specific element to swap the re-rendered component into using the s‑target attribute. In this case we will target the inner HTML of <div id="results">
. We’ll also want to output the search input field and the results div only when the component is included (on the first render), which we can do by checking that sprig.isInclude evaluates to true
.
{# Sets to a default value if not defined #}
{% set query = query ?? '' %}
{% if sprig.isInclude %}
<input sprig s-trigger="keyup changed delay:300ms" s-target="#results" type="text" name="query" value="{{ query }}">
<div id="results"></div>
{% endif %}
{% if query %}
{% set entries = craft.entries().search(query).orderBy('score').all() %}
{% for entry in entries %}
{{ entry.title }}
{% endfor %}
{% endif %}
An easier way of achieving the same result is to use the s‑replace attribute to specify which element to replace. The search input field will still be output in the response HTML, but only the inner HTML of <div id="results">
will be replaced with the new version of itself.
{# Sets to a default value if not defined #}
{% set query = query ?? '' %}
<input sprig s-trigger="keyup changed delay:300ms" s-replace="#results" type="text" name="query" value="{{ query }}">
<div id="results">
{% if query %}
{% set entries = craft.entries().search(query).orderBy('score').all() %}
{% for entry in entries %}
{{ entry.title }}
{% endfor %}
{% endif %}
</div>
View the live demo.
Component Variables #
When creating a new component, you can pass it one or more variables that will become available in the template, as an object in the second parameter.
{# Creates a component from the template path #}
{{ sprig('_components/search', {
query: 'Wally',
}) }}
Only primitive data types can be used as values: strings, numbers, booleans and arrays. Objects, models and elements cannot be used. If you want to pass an element (or set of elements) into a Sprig component then you should pass in an ID (or array of IDs) instead and then fetch the element from within the component.
{# Passes an entry ID into the component #}
{{ sprig('_components/entry', {
entryId: 1,
}) }}
{# Passes an array of entry IDs into the component #}
{{ sprig('_components/entries', {
entryIds: [1, 2, 3],
}) }}
{#-- _components/entry.twig --#}
{% set entry = craft.entries.id(entryId).one() %}
{#-- _components/entries.twig --#}
{% set entries = craft.entries.id(entryIds).all() %}
Note that any variables passed into a Sprig component will be visible in the source code in plain text, so you should avoid passing in any sensitive data.
If you want to pass a variable into the component that cannot be modified or tampered with, prefix it with an underscore. It will still be readable but it will also be hashed so that it cannot be deliberately modified by users without an exception being thrown.
{# Creates a component with a protected variable #}
{{ sprig('_components/search', {
_section: 'news',
}) }}
Request parameters (query string and body parameters) are automatically available in your components, provided they do not begin with an underscore.
{# 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” #}
The following component will output entries, offset by and limited to the provided values (initially 0
and 1
). Since the _limit
variable is prefixed with an underscore, it cannot be tampered with.
{#-- main.twig --#}
{# Creates a component from the template path #}
{{ sprig('_components/load-more', {
offset: 0,
_limit: 1,
}) }}
{#-- _components/load-more.twig --#}
{% set entries = craft.entries.offset(offset).limit(_limit).all() %}
{% for entry in entries %}
<p>{{ entry.title }}</p>
{% endfor %}
{% if entries %}
<div id="replace">
<input type="hidden" name="offset" value="{{ offset + _limit }}">
<button sprig s-target="#replace" s-swap="outerHTML">Load more</button>
</div>
{% endif %}
We’ve used a div
with an ID of replace
, which we use as the target to load more entries into. In it, we put a hidden input
field in which we can increment the offset by the limit value, as well as a load more button that targets its parent element. We set the s‑swap attribute on the button to outerHTML
to ensure that the entire div
is replaced (by default only the inner HTML is). We’ve wrapped the div
in a conditional so it will be output only if entries are found.
An alternative way of dynamically adding or modifying parameters in our components is to use the s‑vals attribute (it expects a JSON encoded list of name-value pairs). This differs from using an input
field because it will be submitted with the request only when the button
element is clicked.
<button sprig s-vals="{{ { offset: offset + _limit }|json_encode }}" s-target="this" s-swap="outerHTML">Load more</button>
The s‑val:* attribute provides a more readable way of populating the s-vals
attribute. Replace the *
with a lower-case name (in kebab-case
, dashes will be removed and the name will be converted to camelCase
).
<button sprig s-val:offset="{{ offset + _limit }}" s-target="this" s-swap="outerHTML">Load more</button>
View the live demo.
A more complex load more example is available in this cookbook recipe.
Component Attributes #
When creating a new component, you can assign it one or more attributes, as a hash in the third parameter. Attributes beginning with s-
can be used to apply logic to the component element itself.
{{ sprig('_components/search', {}, {
'id': 'search-component',
's-trigger': 'load, refresh',
}) }}
The example above makes it possible to trigger the component to refresh itself on load
, as well as whenever we manually trigger a refresh
event using JavaScript.
Components are assigned a trigger called
refresh
by default, which can be overridden using thes-trigger
attribute as in the example above.
<script>
// Using Vanilla JS:
document.getElementById('search-component').dispatchEvent(new Event('refresh'));
// Using htmx JS API:
htmx.trigger('#search-component', 'refresh');
</script>
Watch the CraftQuest livestream on how to use Sprig to inject dynamic content into statically-cached pages.
Component State #
Since a component can be re-rendered at any time, it is important to understand that its state (the variables available to it) can also change at any time. The variables available in a component are determined as follows (values defined later take precedence):
- Component variables passed in through the
sprig()
function. - The values of all request parameters (query string and body parameters).
- The values of all
input
fields (includingtextarea
andselect
fields), if the component is re-rendered. - The values of
s-val:*
ands-vals
attributes on the triggering element (as well as on all its surrounding elements), if the component is re-rendered. - Template variables defined by Craft, plugins and controller actions.
If you want a variable to persist across multiple requests then you can achieve this by adding a hidden input field anywhere inside the component.
{# Limit will always be set to `10` %}
{{ hiddenInput('limit', 10) }}
{# Page will always be set to the previous value, or `1` if none was defined %}
{{ hiddenInput('page', page ?? 1) }}
Controller Actions #
We can call Craft as well as plugin/module controller actions using the s‑action attribute. Let’s take the example of an “add to cart” form (similar to the one shown in the Commerce docs).
<form method="post">
<input type="hidden" name="action" value="commerce/cart/update-cart">
{{ csrfInput() }}
<input type="hidden" name="purchasableId" value="{{ variant.id }}">
<input type="submit" value="Add to cart">
</form>
To make this a reactive component, we’ll add the sprig
attribute to the form, as well as the s‑method and s‑action attributes. Since this is a POST request, Sprig will take care of adding the CSRF token for us, so we can adjust our form as follows.
<form sprig s-method="post" s-action="commerce/cart/update-cart">
<input type="hidden" name="purchasableId" value="{{ variant.id }}">
<input type="submit" value="Add to cart">
</form>
Next, let’s add an appropriate message on submission. The update-cart
action will return a success
value, as well as a flash notice or error, depending on the value of success
. Sprig will load those return values into template variables for us, so we can use them as follows.
<form sprig s-method="post" s-action="commerce/cart/update-cart">
<input type="hidden" name="purchasableId" value="{{ variant.id }}">
<input type="submit" value="Add to cart">
</form>
{% if success is defined %}
<p class="notice">
{{ success ? flashes.notice : flashes.error }}
</p>
{% endif %}
As in the example above, some controller actions set flash messages which you can access using the flashes
variable.
{# Gets and outputs all flash messages. #}
{% set flashes = flashes ?? [] %}
{% for key, message in flashes %}
<p class="{{ key }}">
{{ message }}
</p>
{% endfor %}
{# Gets specific flash messages. #}
{% set flashNotice = flashes.notice ?? '' %}
{% set flashError = flashes.error ?? '' %}
Triggers #
Any HTML element can be made reactive by adding the sprig
attribute to it inside of a component. By default, the “natural” event of an element will be used as the trigger:
input
,textarea
andselect
elements are triggered on thechange
event.form
elements are triggered on thesubmit
event.- All other elements are triggered on the
click
event.
If you want to specify different trigger behaviour, use the s‑trigger attribute.
<div sprig s-trigger="mouseenter">
Mouse over me to re-render the component.
</div>
If you want a trigger to only happen once, you can use the once
modifier for the trigger.
<div sprig s-trigger="mouseenter once">
Mouse over me to re-render the component only once.
</div>
Triggers are very powerful and essential to understanding how to do more complex things with Sprig. View all of the available trigger events and modifiers.
Component Classes #
In the examples above, we passed a template path into the sprig()
function, which created a component directly from that template. If you want to have more control over the component and be able to use PHP logic then you can create a Component class.
Watch the CraftQuest livestream on Sprig Components as PHP Classes.
First, create a new folder called sprig/components
in your project’s root directory. This is where your Component classes should be created. In order for our Component classes to be autoloaded, we need to add the following to the project’s composer.json
file.
"autoload": {
"psr-4": {
"sprig\\components\\": "sprig/components/"
}
},
Running composer dump
will regenerate the optimized autoload files for us.
Let’s create a file called ContactForm.php
for our base component.
<?php
namespace sprig\components;
use putyourlightson\sprig\base\Component;
class ContactForm extends Component
{
}
In most cases, you’ll want the component to render a template. This can be done by setting a protected property $_template
to the template path. All of the public properties of the class will be automatically be available as variables in the template.
<?php
namespace sprig\components;
use putyourlightson\sprig\base\Component;
class ContactForm extends Component
{
public bool $success = false;
public string $error = '';
public string $email = '';
public string $message = '';
protected ?string $_template = '_components/contact-form';
public function send(): void
{
$this->success = SomeEmailApi::send([
'email' => $this->email,
'message' => $this->message,
]);
if (!$this->success) {
$this->error = SomeEmailApi::getError();
}
}
}
We added a send
action as a public method in our class which we can call using the s-action
attribute.
{#-- _components/contact-form --#}
{% if success %}
Thank you for getting in touch!
{% else %}
{% if error %}
<p class="error">{{ error }}</p>
{% endif %}
<form sprig s-action="send">
<input type="email" name="email" value="{{ email }}">
<input type="text" name="message" value="{{ message }}">
</form>
{% endif %}
If you prefer then you can override the render
method which will be called each time the component is rendered.
public function render(): string
{
return 'Contact us by email at [email protected]';
}
Now we can create the component from our ContactForm
class as follows, passing in any variables as before.
{#-- main.twig --#}
{# Creates a component from the ContactForm class #}
{{ sprig('ContactForm', {
message: 'Say hello',
}) }}
View the live demo.
Security Considerations #
Any variables passed into a Sprig component will be visible in the source code in plain text, so you should avoid passing in any sensitive data. Variables can also be overridden (unless prefixed it with an underscore) by manipulating the query string and source code, so you should validate that a variable value is allowed if it could lead to revealing sensitive data.
{% 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() %}
%}
The code above will only fetch the entries in the provided section if it is either articles
or plugins
. This avoids the possibility that someone could change section
to secrets
and gain access to entries that should not be visible. See an example using protected variables here.
Since variables can contain user input, you should be aware of the risk of introducing a Cross-Site Scripting (XSS) vulnerability into your code. Variables output by Twig are automatically escaped, but you should always ensure that your HTML attribute values are wrapped in quotes and that you escape any variables that are output inside of script
tags using the JavaScript escape filter.
{# It is unsafe to omit quotes, do NOT do this. #}
<div s-val:name={{ name }}>
{# It is safe to use either double or single quotes. #}
<div s-val:name="{{ name }}">
<div s-val:name='{{ name }}'>
<script>
{# Escape for JavaScript. #}
console.log('{{ name|escape('js') }}');
</script>
Live Demos #
For more real-world examples of using Sprig with Craft, check out the Sprig Cookbook.
Playground #
Sprig comes with a playground that is available in the control panel. The playground allows you to quickly experiment with a default Sprig component, as well as create and save your own.
Component variables can be passed in separated by ampersands, for example count=0&limit=5
. The playground can be disabled on a per environment basis using the enablePlayground
config setting.
Htmx #
Sprig requires and uses htmx (~10 KB gzipped) under the hood, although it tries to remain as decoupled as possible by not providing any JavaScript code of its own.
Listen to devMode.fm podcast on htmx.
Anything you can do with hx-
attributes you can also do with s-
and sprig-
attributes. If you insist on having valid HTML then you can prefix all Sprig attributes with data-
(data-sprig
, data-s-action
, etc.). See the full attribute reference.
You can load htmx by placing the {{ sprig.script }}
tag near the end of your page’s body
tag. This is the recommended way of doing so, because Sprig can then select the appropriate version of htmx.
{# Loads htmx #}
{{ sprig.script }}
Alternatively, you can download and host the htmx source code on your own server or install the package using npm.
npm install htmx.org
The drawback to this approach is that you’ll need to manually update htmx and ensure that you use the same version that Sprig uses.
JavaScript #
Any <script>
tags containing JavaScript code in your components will be executed when a component is re-rendered.
<script>
console.log('I was just re-rendered.');
</script>
Be careful when outputting variables that could include user input inside script
tags as this can lead to XSS vulnerabilities (see security considerations). Ideally you should escape all variables using the |escape('js')
(or e|('js')
) filter.
<script>
console.log('{{ message|escape('js') }});
</script>
The htmx JS API provides a simplified way of performing common tasks. The code below shows how to trigger the refresh
event on an element with ID search-component
using the htmx JS API and vanilla JS.
<script>
// Using htmx JS API:
htmx.trigger('#search-component', 'refresh'));
// Using Vanilla JS:
document.getElementById('search-component').dispatchEvent(new Event('refresh'));
</script>
Alternatively, you can use a htmx event such as htmx:afterSwap
to run a function after a component is re-rendered and swapped into the DOM. The following code should exist in or be called from the parent template.
<script>
htmx.on('htmx:afterSwap', function(event) {
// do something
});
</script>
Alpine.js #
If using Alpine.js, you should always opt to use inline directives over runtime declarations, for example use x‑data over Alpine.data.
{# Do this. #}
<div x-data="{ open: false, toggle() { this.open = !this.open } }">
<button x-on:click="toggle">Toggle Content</button>
<div x-show="open">
Content...
</div>
</div>
{# DON'T do this! #}
<div x-data="dropdown">
<button x-on:click="toggle">Toggle Content</button>
<div x-show="open">
Content...
</div>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('dropdown', () => ({
open: false,
toggle() {
this.open = !this.open
},
}))
})
</script>
Alpine’s Persist plugin is useful for persisting Alpine state across component re-renders, in addition to page loads.
<div x-data="{ count: $persist(0) }">
<button x-on:click="count++">Increment</button>
<span x-text="count"></span>
</div>
<button sprig>Refresh</button>
Attributes #
The following attributes are available. Some are specific to Sprig while others map directly to hx-
attribute equivalents in htmx. See the full attribute reference.
Sprig attribute autocomplete support is available in IDEs via the JetBrains plugin and Visual Studio Code extension.
s-action
#
Sends an action request to the provided controller action.
<form sprig s-action="plugin-handle/controller/action">
Most controller actions require that the method be set to post
and will return a variable called success
(set to true
on success, otherwise false
or undefined) and/or errors
(set to an array of error messages if defined), however each controller action may return different variables according to its response.
<form sprig s-method="post" s-action="commerce/cart/update-cart">
<input type="hidden" name="purchasableId" value="{{ variant.id }}">
<input type="submit" value="Add to cart">
</form>
{% if success is defined and success %}
Product added to your cart!
{% elseif errors is defined %}
{% for error in errors %}
<p class="error">{{ error|first }}</p>
{% endfor %}
{% endif %}
s-boost
#
Boosts normal anchors and form tags to use AJAX instead.
s-confirm
#
Shows a confirm()
dialog before issuing a request.
<button sprig s-confirm="Are you sure you wish to delete this entry?">Delete</button>
Attribute reference »
Cookbook recipe »
s-disable
#
Disables htmx processing for an element and its children. Useful for prevent malicious scripting attacks when you output untrusted user-generated content that may contain HTML tags (see htmx security).
<div s-disable>
{{ entry.untrustedContent }}
<div>
s-disinherit
#
Allows you to control attribute inheritance.
s-encoding
#
Allows you to change the request encoding from the usual application/x-www-form-urlencoded
to multipart/form-data
, useful for when you want to support file uploads.
<form sprig s-method="post" s-action="entries/save-entry" s-encoding="multipart/form-data">
s-ext
#
Enables an htmx extension for an element and all its children.
s-headers
#
Allows you to add to the headers that will be submitted with an AJAX request.
s-history
#
Allows you to prevent sensitive data being saved to the localStorage cache when taking a snapshot of the page state.
s-history-elt
#
Allows you to specify the element that will be used to snapshot and restore page state during navigation.
s-include
#
Includes additional element values in AJAX requests.
s-indicator
#
The element to put the htmx-request
class on during the AJAX request.
s-listen
#
Allows you to specify one or more components (as CSS selectors, separated by commas) that when refreshed, should trigger a refresh on the current element. This attribute is most commonly placed on a component using the third parameter of the sprig
function.
{{ 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'}) }}
s-method
#
Forces the request to be of the type provided. Possible values are get
(default) or post
. If set to post
, Sprig automatically sends a CSRF token in the request.
<form sprig s-method="post">
s-on
#
Allows you to respond to events directly on an element.
<div s-on="click: alert('Clicked!')">Click</div>
s-params
#
Filters the parameters that will be submitted with a request.
s-preserve
#
Ensures that an element remains unchanged even when the component is re-rendered. The value should be set to true
and the element must have an id
.
<iframe id="video" s-preserve="true"></iframe>
s-prompt
#
Shows a prompt before submitting a request.
<button sprig s-prompt="Enter “delete” to confirm deletion.">Delete</button>
s-push-url
#
Pushes a URL into the URL bar and creates a new history entry.
Attribute reference »
Cookbook recipe »
s-replace
#
Specifies the element to be replaced. The entire component is returned in the response, but only the specified element is replaced. This is equivalent to combining s-select
, s-target
and s-swap
.
<input name="query" sprig s-replace="#results">
{# Equivalent to: #}
<input name="query" sprig s-select="#results" s-target="#results" s-swap="outerHTML">
s-replace-url
#
Allows you to replace the current URL of the browser location history.
s-request
#
Allows you to configure various aspects of the request.
s-select
#
Selects a subset of the server response to process.
Attribute reference »
Cookbook recipe »
s-select-oob
#
Selects one or more elements from a server response to swap in via an “Out of Band” swap.
s-swap
#
Controls how the response content is swapped into the DOM (outerHTML
, beforeEnd
, etc.).
<input name="query" sprig s-swap="outerHTML" s-target="#results">
Attribute reference »
Cookbook recipe »
s-swap-oob
#
Marks content in a response as being “Out of Band”, i.e. swapped somewhere other than the target.
Attribute reference »
Cookbook recipe »
s-sync
#
Allows you to synchronize AJAX requests between multiple elements.
s-target
#
Specifies the target element to be swapped.
<input name="query" sprig s-target="#results">
Attribute reference »
Cookbook recipe »
s-trigger
#
Specifies the event that triggers the request.
<input name="query" sprig s-trigger="keyup changed delay:300ms">
Attribute reference »
Cookbook recipe »
s-val:*
#
Provides a more readable way of populating the s-vals
attribute. Replace the *
with a lower-case name.
<button sprig s-val:page="{{ page + 1 }}" s-val:limit="10">Next</button>
{# Equivalent to: #}
<button sprig s-vals="{{ { page: page + 1, limit: 10 }|json_encode }}">Next</button>
Since HTML attributes are case-insensitive, the name should always be lower-case and in kebab-case
. Dashes will be removed and the name will be converted to camelCase
when the variable becomes available in the template after re-rendering.
{% set myCustomPage = myCustomPage ?? '' %}
<button sprig s-val:my-custom-page="13">Custom Page</button>
s-validate
#
Forces an element to validate itself before it submits a request. Form elements do this by default, but other elements do not.
s-vals
#
Adds to the parameters that will be submitted with the request. The value must be a JSON encoded list of name-value pairs.
<button sprig s-vals="{{ { page: page + 1, limit: 10 }|json_encode }}">Next</button>
s-vars
#
The
s-vars
attribute has been deprecated for security reasons. Use the more secure s‑vals or s‑val:* instead.The expressions in
s-vars
are dynamically computed which allows you to add JavaScript code that will be executed. While this is a powerful feature, it can lead to a Cross-Site Scripting (XSS) vulnerability if user input is included in expressions. If you absolutely require dynamically computed expressions then use hx-vars directly.
Adds to the parameters that will be submitted with the request. The value must be a comma-separated list of name-value pairs.
<button sprig s-vars="page: {{ page + 1 }}, limit: 10">Next</button>
Template Variables #
Sprig provides the following template variables.
sprig.script
#
Outputs a script
tag that loads htmx. This is the recommended way of loading htmx because Sprig can select the appropriate version.
{{ sprig.script }}
sprig.setConfig(options)
#
Allows you to set configuration options for htmx (via a meta tag).
{% do sprig.setConfig({ indicatorClass: 'loading' }) %}
sprig.paginate(query, page)
#
Paginates a query and returns a variable (that extends Craft’s Paginate variable) that contains the current page results and information.
The sprig.paginate
method accepts a query (an element query or an active query) and a page number (defaults to 1) and returns a variable that provides the following properties and methods:
pageInfo.pageResults
– The element results for the current page.pageInfo.first
– The offset of the first element on the current page.pageInfo.last
– The offset of the last element on the current page.pageInfo.total
– The total number of elements across all pagespageInfo.currentPage
– The current page number.pageInfo.totalPages
– The total number of pages.pageInfo.getRange(start, end)
– Returns a range of page numbers as an array.pageInfo.getDynamicRange(max)
– Returns a dynamic range of page numbers that surround (and include) the current page as an array.
{% 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 }}.
sprig.location(url)
#
Triggers a client-side redirect without reloading the page.
{% do sprig.location('/page' ~ page) %}
sprig.pushUrl(url)
#
Pushes the URL into the URL bar and creates a new history entry.
{% do sprig.pushUrl('?page=' ~ page) %}
sprig.redirect(url)
#
Forces the browser to redirect to the URL.
{% do sprig.redirect('/new/page') %}
sprig.refresh()
#
Forces the browser to refresh the page.
{% do sprig.refresh() %}
sprig.replaceUrl(url)
#
Replaces the current URL in the location bar.
{% do sprig.replaceUrl('/page' ~ page) %}
sprig.reswap(value)
#
Allows you to change the swap behaviour.
{% do sprig.reswap('outerHTML') %}
sprig.retarget(target)
#
Overrides the target element via a CSS selector.
{% do sprig.retarget('#results') %}
sprig.triggerEvents(events)
#
Triggers one or more client-side events. The events
parameter can be a string or an array of strings.
{% do sprig.triggerEvents('eventA') %}
{% do sprig.triggerEvents('{"eventA":"A message"}') %}
{% do sprig.triggerEvents(['eventA', 'eventB', 'eventC']) %}
sprig.triggerRefreshOnLoad(selector)
#
Triggers a refresh of the Sprig components matching the selector, or all components (using the default selector .sprig-component
) on page load. This is especially useful when statically caching pages to avoid CSRF requests failing on the first cached request, see this issue for details.
{{ sprig.triggerRefreshOnLoad() }}
sprig.isInclude
#
Returns true
if the template is being rendered on initial page load (not through an AJAX request), otherwise, false
.
{% if sprig.isInclude %}
Template rendered on initial page load
{% else %}
Template rendered through an AJAX request
{% endif %}
sprig.isRequest
#
Returns true
if the template is being rendered through an AJAX request (not on initial page load), otherwise, false
.
{% if sprig.isRequest %}
Template rendered through an AJAX request
{% else %}
Template rendered on initial page load
{% endif %}
sprig.isBoosted
#
Returns true
if this is in response to a boosted request (hx-boost).
sprig.isHistoryRestoreRequest
#
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.
sprig.prompt
#
Returns the value entered by the user when prompted via s‑prompt.
sprig.target
#
Returns the ID of the target element.
sprig.trigger
#
Returns the ID of the element that triggered the request.
sprig.triggerName
#
Returns the name of the element that triggered the request.
sprig.url
#
Returns the URL that the Sprig component was loaded from.
Control Panel Usage #
The Sprig Core module provides the core functionality for the Sprig plugin. If you are developing a Craft custom plugin or module and would like to use Sprig in the control panel, then you can require this package to give you its functionality, without requiring that the site has the Sprig plugin installed.
First require the package in your plugin/module’s composer.json
file.
{
"require": {
"putyourlightson/craft-sprig-core": "^2.0"
}
}
Then bootstrap the Sprig module from within your plugin/module’s init
method.
use craft\base\Plugin;
use putyourlightson\sprig\Sprig;
class MyPlugin extends Plugin
{
public function init(): void
{
parent::init();
Sprig::bootstrap();
}
}
You can then use the Sprig function and tags as normal in your control panel templates.
Acknowledgements #
This plugin stands on the shoulders of giants.
- Inspired by Laravel Livewire.
- JavaScript goodness provided by htmx.
- Built for the excellent Craft CMS.
Special thanks goes out to Andrew Welch (nystudio107) and to Z
(you know who you are) for being a source of valuable input.