Skip to content

Instantly share code, notes, and snippets.

@bencroker
Forked from piotrpog/product.twig
Last active November 3, 2020 22:35
Show Gist options
  • Save bencroker/cfb48f8a9bae5a2cc2629e2785a7d000 to your computer and use it in GitHub Desktop.
Save bencroker/cfb48f8a9bae5a2cc2629e2785a7d000 to your computer and use it in GitHub Desktop.
Commerce product page with Sprig
{% set variantParam = 'variant' %}
{# set product #}
{% set product = craft.products.id(productId).one() %}
{# set variant #}
{% set variant = product.defaultVariant %}
{# overvrite default variant with url param #}
{% if product.variants|filter(v => v.id == craft.app.request.getParam(variantParam)) is not empty %}
{% set variant = product.variants|filter(v => v.id == craft.app.request.getParam(variantParam))|first %}
{% endif %}
{# product content #}
<h1>{{ product.title }}</h1>
<div id="sprig">
{# show price #}
Price: {{ variant.price|commerceCurrency }}
{# basket #}
<form action="">
{{ actionInput('commerce/cart/update-cart') }}
{{ csrfInput() }}
{{ hiddenInput('purchasableId', variant.id) }}
<button>Add to cart</button>
</form>
{# variant switcher #}
{% if product.variants|length > 1 %}
<div class="variant-widget">
{% for option in product.variants %}
<button
sprig
s-push-url="?{{ variantParam ~ '=' ~ option.id }}"
s-target="#sprig"
s-swap="outerHTML"
s-vars="{{ variantParam }}: {{ option.id }}"
s-indicator="#preloader"
class="{{ variant.id == option.id ? 'is-selected' }}"
>
{{ option.sku }}
</button>
{% endfor %}
</div>
{% endif %}
{# preloader #}
<div id="preloader">
Loading
</div>
</div>
{% extends 'shop/_layouts/main' %}
{% block main %}
{# show/hide preloader #}
<style>
#preloader {
display: none;
}
#preloader.htmx-request {
display: block;
}
</style>
{{ sprig('_productComponent', { productId: product.id }) }}
{{ sprig.script }}
{% js %}
document.body.addEventListener('htmx:afterSwap', function(evt) {
// reinitialize js scripts
});
{% endjs %}
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment