user15707368
user15707368

Reputation: 3

Storing product line_items in an associative array with vendors

When generating a "Order confirmation" email I'd like a list of the products sorted in "arrays" based on the vendor.

But I can't figure out how to setup product line items to be associated with there vendor.

Here is what I'm trying;

{% assign vendor_count = 0 %}
{% capture vendor_check %}
    {% for line in line_items %}
        {{ line.product.vendor }}{% if forloop.last != true %},{% endif %}
    {% endfor %}
{% endcapture %}

{% assign line_vendor = vendor_check | split: ',' | uniq %}

{%- assign vendor_items = line_items | where: "vendor", vendor -%}

{% for vendor in line_vendor %}
      {% assign vendor_count = vendor_count | plus: 1 %}
      <div><strong>Delivery {{ vendor_count }} - {{ vendor }}</strong></div>
      {% for line in vendor_items %}
          {{ line.title }}<br>      
      {% endfor %}  
{% endfor %}

Current output:

Delivery 1 - Vendor#1
Product 1
Product 2
Product 3
Product 4

Delivery 2 - Vendor#2
Product 1
Product 2
Product 3
Product 4

Desired output:

Delivery 1 - Vendor#1
Product 1
Product 2

Delivery 2 - Vendor#2
Product 3
Product 4

What am I doing wrong here?

Upvotes: 0

Views: 198

Answers (1)

cMarius
cMarius

Reputation: 1132

Having indented liquid code can mess up captured variables by inserting unintended white spaces, either have the whole capture tag on 1 line or escape the white spaces.

vendor_items is not really needed, just make an array of unique vendors from line_items, then iterate through your line_items again and display the matching products.

You can try something like this and adapt it to your needs:

{% capture vendor_check %}{% for line in line_items %}{{ line.product.vendor }}{% if forloop.last != true %},{% endif %}{% endfor %}{% endcapture %}

{% assign line_vendor = vendor_check | split: "," | uniq %}

{% for vendor in line_vendor %}
      {% assign vendor_count = vendor_count | plus: 1 %}
      <div><strong>Delivery {{ vendor_count }} - {{ vendor }}</strong></div>

      {% for line in line_items %}
          {% if line.product.vendor == vendor %}{{ line.title }}{% endif %}<br>
      {% endfor %}  
{% endfor %}

Upvotes: 1

Related Questions