mwalker
mwalker

Reputation: 33

Examine cart in Shopify

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

Upvotes: 1

Views: 153

Answers (2)

Radhesh Vayeda
Radhesh Vayeda

Reputation: 901

I think this steps may help you...

Step 1: Create different section instead of snippets for two different types of vendors and default

Step 2: Follow the below code in cart.liquid

{% assign vendor = '' %}
{% assign same = true %}
{% for item in cart.items %}
    {% if vendor != '' or vendor == item.vendor %}
         {% assign vendor = item.vendor %}
    {% else%}
         {% assign same = false %}
    {% endif %}
{% endfor %}

{% if same == true %}
    {% if vendor == 'Brand A' %}
       {% section 'cart-a' %}
    {% elsif vendor == 'Brand B'%}
       {% section 'cart-b' %}
    {% else %}
       {% section 'cart-default' %}
    {% endif %}
{% else %}
    {% section 'cart-default' %}
{% endif %}

Upvotes: 2

Victor Leontyev
Victor Leontyev

Reputation: 8736

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

Upvotes: 1

Related Questions