Sprig Logo Sprig

A reactive Twig component framework for Craft.

Create reactive components from Twig templates and/or PHP classes.

Components can re-render themselves on user-triggered events.

Developer friendly, simple and infinitely extensible.

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.

Inspired entirely by Laravel Livewire, built specifically for Craft with a focus on developer experience and simplicity.

Want to see what Sprig can do right away? Check out the Sprig Cookbook »

Sprig is currently in beta. Please report any bugs or issues in Github »

Sprig

License #

This plugin is licensed for free under the MIT License.

Requirements #

Craft CMS 3.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:1.0.0-beta.5

Usage #

How it Works #

Take the following Twig template which contains a combined search form and results page (similar to that in the Craft docs).

{#-- main.twig --#}

{% set query = craft.app.request.getParam('query') %}

<form>
    <input type="search" name="query" value="{{ query }}">
    <input type="submit" value="Search">
</form>

<div id="results">
    {% if query %}
        {% set entries = craft.entries().search(query).orderBy('score').all() %}
        {% for entry in entries %}
            {{ entry.title }}
       {% endfor %}
    {% endif %}
</div>

We can turn this template into a component using the sprig() function, passing in a template path (just like you might do with an include). Note that in this case, a component” is just another name for a reactive Twig template.

{#-- main.twig --#}

{# Creates a component from the template path #}
{{ sprig('_components/search') }}

{# Output the required script from a CDN, or use your own build process #}
{{ sprig.script }}
{#-- _components/search.twig --#}

{% set query = craft.app.request.getParam('query') %}

<form>
    <input type="search" name="query" value="{{ query }}">
    <input type="submit" value="Search">
</form>

<div id="results">
    {% if query %}
        {% set entries = craft.entries().search(query).orderBy('score').all() %}
        {% for entry in entries %}
            {{ entry.title }}
       {% endfor %}
    {% endif %}
</div>

Nothing special so far, but now we can make the component reactive by adding the sprig attribute to any elements that should be react to certain events. 

{% set query = craft.app.request.getParam('query') %}

<form sprig>
    <input type="search" name="query" value="{{ query }}">
    <input type="submit" value="Search">
</form>

Now each time the form is submitted, the component will re-render itself. Any input fields (including textarea and select fields) in the component will become available as template variables, so we don’t need to get them from the request parameters.

{% set query = query ?? '' %}

<form sprig>
    <input type="search" name="query" value="{{ query }}">
    <input type="submit" value="Search">
</form>

Search demo

No full-page requests were harmed in the making of this. View the live demo.

Let’s say we wanted to make the search input field reactive and get rid of the search button completely. We do that by removing the form and 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. We can make it so that the re-render is triggered on keyup events provided the field value has changed, using the s-trigger attribute.

<input sprig s-trigger="keyup changed" type="search" name="query" value="{{ query }}">

Since we only really want to re-render the search results (and not the search input field), we can target a specific element using the s-target attribute. In this case we will target the inner content of the surrounding div with ID results. We’ll also want to output the search input field only when the component is included (on the first render), which we can do by checking that sprig.include evaluates to true.

{% if sprig.include %}
    <input sprig s-trigger="keyup changed" s-target="#results" type="search" 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 %}

Search live demo

View the live demo.

Variables #

When creating a new component, you can pass it one or more variables that will become available in the template. 

{# Creates a component from the template path #}
{{ sprig('_components/search', {
    query: 'Wally',
}) }}

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. 

Only values that can be passed over HTTP requests may be used (strings, numbers, booleans).

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 #}

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,
}) }}

{# Output the required script from a CDN, or use your own build process #}
{{ sprig.script }}
{#-- _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 would be). We’ve wrapped the div in a conditional so it will be output only if entries are found.

Load more demo

View the live demo.

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 that 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 clean up 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 replace the form with a an appropriate message on submission. The update-cart action will return a success value, as well as values for error and errors if there is a problem see this code block. Sprig will load those return values into template variables for us, so we can use them as follows.

{% if success is defined and success %}
    Product added to your cart!
{% else %}
    {% if error is defined %}
        <p class="error">{{ error }}</p>
    {% endif %}

    <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>
{% endif %}

Add to cart demo

Triggers #

Any element can be made reactive by adding the sprig attribute to it. By default, the natural” event of an element will be used as the trigger:

  • input, textarea and select elements are triggered on the change event.
  • form elements are triggered on the submit event.
  • All other elements are triggered on the click event.

If you want different behaviour you can use the s-trigger attribute to specify the trigger.

<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>

View all of the available trigger options.

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.

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 $success;
    public $error;
    public $email;
    public $message;

    protected $_template = '_components/contact-form';

    public function send()
    {
        $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 }}">
        <textarea name="message">{{ message }}</textarea>
    </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',
}) }}

Contact form demo

View the live demo.

Live Demos #

  1. Search
  2. Search Live
  3. Load More
  4. Contact Form Component

For copy-paste examples of using Sprig with Craft, check out the Sprig Cookbook.

Htmx #

Sprig requires and uses htmx (~7 KB gzipped) under the hood, although it tries to remain as decoupled as possible by not providing any JavaScript code of its own. 

Anything you can do with hx- attributes you can also do with s- and sprig- attributes. See the full attribute reference.

You can load htmx directly from a CDN using the {{ sprig.script }} tag. This is the recommended way because Sprig can then select the appropriate version of htmx.

{# Load htmx #}
{{ sprig.script }}

If you prefer to install the package using npm then be sure to install the same version that the plugin uses.

npm install htmx.or[email protected]

Attributes #

Sprig Specific #

The following attributes are specific to Sprig.

s-action #

Sends an action request to the provided controller action.

<form sprig s-action="plugin-handle/controller/action">

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">

Inherited from htmx #

The following attributes are commonly used in Sprig and map directly to their hx- attribute equivalents in htmx. See the full attribute reference.

s-confirm #

Shows a confim() dialog before issuing a request (reference).

<button s-confirm="Are you sure you wish to delete this entry?">Delete</button>

s-include #

Includes additional data in AJAX requests (reference).

s-indicator #

The element to put the htmx-request class on during the AJAX request (reference).

s-params #

Filters the parameters that will be submitted with a request (reference).

s-prompt #

Shows a prompt before submitting a request (reference).

<button s-prompt="Enter the slug of this entry to confirm deletion.">Delete</button>

s-push-url #

Pushes the URL into the location bar, creating a new history entry (reference).

s-select #

Selects a subset of the server response to process (reference).

s-swap #

Controls how the response content is swapped into the DOM (e.g. outerHTML or beforeEnd) (reference).

<input name="query" s-swap="outerHTML" s-target="#results">

s-target #

Specifies the target element to be swapped (reference).

<input name="query" s-target="#results">

s-trigger #

Specifies the event that triggers the request (reference).

<input name="query" s-trigger="keyup changed">

s-vars #

Adds to the parameters that will be submitted with the request (reference).

<button s-vars="page: 2">Next</button>

Acknowledgements #

This plugin stands on the shoulders of giants.

Special thanks to Andrew Welch, John D. Wells and Keyur Shah for being a sounding board and a source of valuable input. Thanks also goes out to Z (you know who you are).

Icon: Herb emoji by Twemoji.