1

I have a changing sort dropdown using Sprig, works great. Though, I'd like to save this sort order to local storage and pass it as the default to my sprig component.

What's the best way to do this? Is there a way to directly pass a JS variable to sprig components?

This is my parent:

{{ sprig('_components/groupCards', {
    entryId: entry.id,
}) }}
   
{% js %}
    document.addEventListener('DOMContentLoaded', function() {
        const sortOrderSelect = document.getElementById('order');

        // Check if a sort order is saved in local storage and update the select element
        const savedOrder = localStorage.getItem('order');
        if (savedOrder) {
            sortOrderSelect.value = savedOrder;
            console.log(savedOrder)
        }
        // Change LocalStorage to the new value of the select box.
        sortOrderSelect.addEventListener('change', function() {
            localStorage.setItem('order', this.value);
        });
    });
{% endjs %}

and my component:

 {# Sprig Empty Variables #}
 {% set order = order ?? ''%}
 {% set entry = craft.entries.id(entryId).one() %}

 {% set entryQuery = craft.entries()
        .section('products')
        .relatedTo(entry)
        .with(['image'])
        .limit(20)
        .orderBy(order)
     %}

{% set count = entryQuery.count() %}

<select sprig name="order" id="order" value="{{ order }}" class="form-control" s-replace="#items">
    <option value="productNumber">Product Number</option>
    <option value="title asc">Title Ascending</option>
</select>

Tried a few different ways, but seem to either run into CORS error's or HTMX errors.

1 Answer 1

2

Does it have to be local storage? If a cookie would work, then you’d be able to achieve this directly via Twig code.

{{ sprig('_components/groupCards', {
    entryId: entry.id,
    order: craft.app.request.cookies.get('order') }}
}) }}

And then in your component:

{% set order = order ?? '' %}
{% if order %}
    {% do craft.app.response.cookies.add(create({
        class: 'yii\\web\\cookie',
        name: 'order',
        value: order,
    })) %}
{% endif %}

Note that getting and setting cookies is easier using the Cookies plugin.

{% set order = getCookie('order') %}
{% set order = order ?? '' %}
{% if order %}
    {% do craft.cookies.set('order', order) %}
{% endif %}
1
  • Thanks Ben, love Sprig. I'll pop it through Cookies ~ I actually thought it'd be easier via localstorage but twig's cookies works too.
    – JMKelley
    Apr 12 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.