Ad

Examine Cart In Shopify

- 1 answer

I'm hoping for some help with liquid in Shopify, I'm having trouble with trying to customise the cart based on what product the customer has added.

Basically if a customer adds product from Vendor A then I want the cart to load the template to customise the cart for Vendor A

But if product is from Vendor B then I want it to load the template to customise the cart for Vendor B

But if the cart has products from neither (or both) then I want it to load the default cart.

{Edit: I worked out what was wrong with my code to load the templates but now I just need help with the logic so that when the cart has products from both brands it loads the default cart. Because at the moment it loads both cart snippets into the page}

Any help massively appreciated!

{% for item in cart.items %}
{% if item.vendor == 'Brand A' %}
{% include 'cart-a' %}
{% elsif item.vendor == 'Brand B' %}
{% include 'cart-b' %}
{% else %}

{% section 'cart-default %}

{% endif %}
{% endfor %}

also tried this:

{% case cart.items %}
{% when item.vendor == 'Brand A' %}
{% include 'cart-a' %}
{% when item.vendor == 'Brand B' %}
{% include 'cart-b' %}
{% when item.vendor == ‘Brand A’ and item.vendor == 'Brand B' %}
{% section 'cart-default' %}
{% else %}
{% section 'cart-default' %}
{% endcase %}
Ad

Answer

In liquid it is easier to work with arrays. Working code for you:

{% assign vendors = cart.items | map: 'vendor'| uniq | join: ' ' %}
{% if  vendors contains "Brand A" and vendors contains "Brand B" %}
    {% section 'cart-default' %}
{% else %}
    {% if  vendors contains "Brand A" %}
        {% section 'cart-a' %}
    {% else %}
        {% if  vendors contains "Brand B" %}
            {% section 'cart-b' %}
        {% else %}  
            {% section 'cart-default' %}
        {% endif %}
    {% endif %}
{% endif %}
Ad
source: stackoverflow.com
Ad