Ad

Dynamic Attribute Names In Shopify Cart

- 1 answer

I'm so close on this, but I just can't get the syntax right. I've been messing with this off and on for days. Essentially I have a greeting card message and I want the message to be filled in by the customer for every Greeting Card on the checkout page (cart.liquid) and I need the attribute name to change for every index. Therefore I'm adding the index to each attribute name, but to no avail. For testing purposes, here's a basic input field:

    <p class="cart-attribute__field" style="min-width:300px;">
      <label for="to{{ forloop.index }}">To:</label>
      <input class="checkMe" id="to{{ forloop.index  }}" type="text" name="attributes[To{{ forloop.index  }}]"  maxlength="40" data-stk="{{item.id}}" value="{{ cart.attributes['To'+forloop.index] }}" >

    </p> 

And its this part (value="{{ cart.attributes['To'+forloop.index] }}") that is giving me trouble.

Ad

Answer

You cannot use '+' operator in liquid code to append. Try this instead:

{% assign cart_attr = 'To' | append: forloop.index %}
<p class="cart-attribute__field" style="min-width:300px;">
<label for="to{{ forloop.index }}">To:</label>
<input class="checkMe" id="to{{ forloop.index  }}" type="text" name="attributes[To{{ forloop.index  }}]"  maxlength="40" data-stk="{{item.id}}" value="{{ cart.attributes[cart_attr] }}" >
</p>

Note: Improvise as required.

Ad
source: stackoverflow.com
Ad