shopifyliquidshopify-template

In shopify How to push product Object to blank Array


In Shopify my code structure follows product loop.

{% assign products = all_products[block.settings.product_to_show] %}

In products variable i got object of one product. but my code structure of for loop only accept products as array.

{% for product in products %}
 {% include 'product-card', product: product %}
{% endfor %}

So how can i push "products" (object) in blank array in shopify?


Solution

  • With Liquid we are generally limited to creating an array of strings (not objects). Given that you seem to have the product handles coming from section block settings, here are some approaches that may work for you:

    1. Use a forloop on section.blocks, create the product object and pass it to the output snippet (Example code assumes there is only 1 product per block).
    {% for block in section.blocks %}
      {% assign _product = all_products[block.settings.product_to_show] %}
      {% include 'product-card', product: _product %}
    {% endfor %}
    
    1. Loop over the section blocks and create a comma separated string of the product handles(strings). Use the split filter to convert the string into and array of strings. Loop over the array, create the product object and pass it to the output snippet.
    {% assign products = '' %}
    {% for block in section.blocks %}
      {% comment %}
        You can place additional logic/conditions within this loop to customize how your "products" array is built
      {% endcomment %}
    
      {% assign products = products | append: block.settings.product_to_show | append: ',' %}
    {% endfor %}
    
    {% assign products = products | split: ',' %}
    
    {% for product_handle in products %}
      {% assign _product = all_products[product_handle] %}
      {% include 'product-card', product: _product %}
    {% endfor %}