How can I use Twig with multiple items in the basket?

I can see the examples for Twig in the Shopblocks admin system at Settings > Twig and I can see how putting things like {{ product.name }} works to show the Product Name on a product page for example.

But - I want to use the customer’s basket and output a list of their items inside some JavaScript to push the data to my external analytics (Google Analytics GA4).

How is this done?

Hi Mike,

In order to do things with Twig where the data is an “array” (a list of items) you can use some special Twig “for” loops.

For example, if you created a HTML code block in BlockLab and added the following, you will get a JavaScript object containing your customer’s basket line items:

<p>Twig loop of basket line items example</p>
<script>
    var arrayOfItems = [
        {% for item in basket.line_items %}
          {
              "sku":"{{ item.sku }}",
              "name":"{{ item.product_name }}",
              "quantity":"{{ item.quantity }}",
              "price_exluding_tax":"{{ item.net_unit_price }}",
              "price_including_tax":"{{ item.gross_unit_price }}",
              "line_total_net":"{{ item.net }}",
              "line_total_gross":"{{ item.gross }}"
          }{% if loop.last == false %},{% endif %}
        {% endfor %}
    ];
</script>

The loop.last == false part ensures a comma is added after each item to make the JavaScript array valid.

If you want to see everything available within the basket line_items data, you can always do something like this in Twig to see it all:

<pre>
{{ basket.line_items | json_encode(constant('JSON_PRETTY_PRINT')) }}
</pre>

You can put any variable in the first part of this example, replacing basket.line_items and when publishing this in your BlockLab design, on your site you should see all of the data in an easily-readable JSON format.

Good luck!