Programming cart attributes with conditionals based on line item properties

I’ve noticed in the Shopify API documentation that the name and value associated with a line item property appear to be accessible with the objects line_item.properties.first and line_item.properties.last.


  {% for property in line_item.properties %}
    - {{ property.first }}: {{ property.last }}
  {% endfor %}

I have assumed that it should be possible to write a for loop for the cart.liquid template that accesses these same objects, using them inside a conditional that would allow certain cart attribute input fields to be added to the cart page only if the customer has added a particular item with a particular line item property value.

This is what my attempt at doing this has looked like:

{% for attr in cart.items %}
{% if attr.properties.first == 'Name' and attr.properties.last == 'Value' %}
  

    
    
  

{% endif %}
{% endfor %}

This is not working in testing when the name and value match up with what is desired for the conditional. Considering the lack of documentation on doing something like this, I’m now thinking that I’m misunderstanding something important about liquid and the Shopify API. Is it possible to write a for loop that can accomplish what I am looking for?

Hello @grz

TV there’s a cart ajax library that you can use to set all this up without having to loop. If you use variants it could be even simpler.

All of this can be done without liquid and the requisite page refreshes.

I do theme development so if you’d prefer I handle this, just message me.

If you’d like further assistance, just let me know.

-David

I managed to figure out what was missing. It wasn’t clear to me from the API docs exactly how the line_item.properties array worked. I needed a nested for loop to accomplish what I intended to achieve.

With the two for loops, the first cycles through the items in the cart, and the nested one takes the line item properties for each item one by one.

{% for item in cart.items %}
  {% for attr in item.properties %}
  {% if attr.first == 'Name' and attr.last == 'Value' %}
    

      
      
    

  {% endif %}
  {% endfor %}
{% endfor %}