Ad

How To Add Iterations On This Liquid For Loop

- 1 answer

How i add a numbers iterating on this for loop in place of {{i}} Please note that this loop dont have a specific limit since it will get all ordered items no matter how many are them.

<img src="https://billiger.de/sale?shop_id=Acaraa&oid={{ order.order_number }}

{% for line_item in order.line_items %}
&aid_{{i}}={{ line_item.product_id }}&name_{{i}}={{ line_item.product.title }}&cnt_{{i}}={{ line_item.quantity }}&val_{{i}}={{ line_item.product.price | divided_by: 1.19  | times: line_item.quantity | money_without_currency}}
{% endfor %}

" width="1" height="1" border="0" alt="" />

So the loop should look like this

&aid_1=ARTICLE-ID-1&name_1=ARTICLE-NAME-1&cnt_1=ARTICLE-COUNT-1&val_1=ARTICLE-VALUE-1
&aid_2=ARTICLE-ID-2&name_2=ARTICLE-NAME-2&cnt_2=ARTICLE-COUNT-2&val_2=ARTICLE-VALUE-2
&aid_3=ARTICLE-ID-3&name_3=ARTICLE-NAME-3&cnt_3=ARTICLE-COUNT-3&val_3=ARTICLE-VALUE-3

PS: The above code will be used in shopify template file

Thanks

Ad

Answer

The forloop object has a number of helper methods, including ones to count the current iteration of a loop:

  • forloop.index which counts the loop iteration starting from 1
  • forloop.index0 which counts the loop iteration starting from 0

In your example you would modify your code to use the appropriate method instead of {{i}}; i.e:

<img src="https://billiger.de/sale?shop_id=Acaraa&oid={{ order.order_number }}

{% for line_item in order.line_items %}
&aid_{{forloop.index}}={{ line_item.product_id }}&name_{{forloop.index}}={{ line_item.product.title }}&cnt_{{forloop.index}}={{ line_item.quantity }}&val_{{forloop.index}}={{ line_item.product.price | divided_by: 1.19  | times: line_item.quantity | money_without_currency}}
{% endfor %}

" width="1" height="1" border="0" alt="" />

I am assuming you want to start counting the iterations from 1 here, but just use forloop.index0 if you want to start from 0.

Here is the documentation for forloop.index for Shopify's official Liquid library (in Ruby).

Since you have tagged your question as PHP, it would appear that you are using the php-liquid port of the library - it appears in Shopify's list of Liquid ports.

This port does not seem to have any detailed documentation but if you look at the unit tests you'll see that these forloop helpers have been implemented.

Hope this helps :)

Ad
source: stackoverflow.com
Ad