skip to Main Content

I’m doing the following using JS with liquid:

const variantsWithInventoryData = {};

// Loop through each variant and assign to the object
{% for variant in product.variants %}
  variantsWithInventoryData["{{ variant.id }}"] = {
    inventory_quantity: {{ variant.inventory_quantity }},
    inventory_policy: "{{ variant.inventory_policy }}",
    inventory_management: "{{ variant.inventory_management }}",
    inventory_item_id: 0
  };
{% endfor %}

How can I achieve the above entirely using liquid?

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    1st I've looped over the variants using only liquid inside a script with a id and then I fetched the required data by parsing the data inside that script element. Here's the implementation:

    {% comment %} Separate Liquid Code START {% endcomment %}
    <script type="application/json" id="inventory-data">
      {
        {% for variant in product.variants %}
          "{{ variant.id }}": {
            "inventory_quantity": {{ variant.inventory_quantity }},
            "inventory_policy": "{{ variant.inventory_policy }}",
            "inventory_management": "{{ variant.inventory_management }}",
            "inventory_item_id": 0
          }
          {% unless forloop.last %},{% endunless %}
        {% endfor %}
      }
    </script>
    
    <script>
      // Fetch the JSON from the script tag
      const inventoryDataFromElement = document.getElementById('inventory-data');
      let varsWithInventoryData;
    
      varsWithInventoryData = JSON.parse(inventoryDataFromElement.textContent);
      window.varsWithInventoryData = varsWithInventoryData;
      console.log(varsWithInventoryData); 
    </script>
    {% comment %} Separate Liquid Code END {% endcomment %}
    

  2. 
    {% for variant in variants %}
            {% assign id = variant.id %}
            {% assign size = variant. quantity %} // remove space after "." 
            {% assign color = variant. color %} // remove space after "."
            {% assign res = res | append: id %}
            {% assign res = res | append: " (" %}
            {% assign res = res | append: size %}
            {% assign res = res | append: ", " %}
            {% assign res = res | append: color %}
            {% assign res = res | append: "); " %}
    
    {% endfor %}
    
    {{ res }}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search