2

I want to cache the cart using key cart.id to save some db queries.

{% set cart = craft.commerce.cart %}

{% cache globally using key "cartId=" ~ cart.id ?? "empty" until cart.dateUpdated %}

{% if cart.lineItems | length %}
    {% for item in cart.lineItems %}
        {{ item.sku }},
    {% endfor %}
{% else %}
    <p>Cart has no items</p>
{% endif %}

{% endcache %}
  1. Is caching by cart.id sufficient?
  2. Is there any potential risk?
  3. What is {% set cart = craft.commerce.cart %} actually setting when cart.id = null ?
5

Is caching by cart.id sufficient?

I would not cache the cart, it could always be changing. You would need to create a cache ID based on every aspect of the cart that could change (line items, coupons, addresses, sales, discounts, tax etc). Bottom line, do not cache dynamic things like the cart.

Is there any potential risk?

See above.

What is {% set cart = craft.commerce.cart %} actually setting when cart.id = null ?

You are getting an order model returned, it just does not get an ID until the first item is added to the cart and the order/cart is saved to the database.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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