The foreach
loop starts with the foreach
tag and ends with the endforeach
tag. It is used to iterate through a certain amount of data (arrays) with properties and limitations.
For example, if you have 15 different products that fit a certain product recommendation rule, you can display only 5 of them, along with the name, color and price of those 5 products.
To ensure that only 5 products are shown, you need to specify 5 within the foreach properties.The foreach loop will execute this command and only display 5 of the 15 products. If only 2 products meet the conditions, then only those 2 will be displayed (the limitation applies to the maximum number of items.)
The foreach loop in the following example loops through the email addresses of different store locations. We only would like to display 3 of them, so it will stop at the 3rd one, as the limit is set to the 3rd element. The default and maximum limit is 100.
{% foreach value in [‘lastore@lifestylelabels.com’,‘chicagostore@lifestylelabels.com’,‘philadelphiastore@lifestylelabels.com’,’seattlestore@lifestylelabels.com’, ‘dallasstore@lifestylelabels.com’] limit 3 %}
{{ value }}
{% endforeach %}
This is how the email will look like:
You can also use the foreach
loop to display numeric values. For example:
{% foreach value in [1, 2, 3, 4] limit 3 %}
{{ value }}
{% endforeach %}
This is how the email will look like:
You can also put text or numeric values within the brackets [ ]
. When you use text, make sure each value is enclosed within ' '
characters. The foreach
loop will iterate through these items and list the specified quantity.
A complex foreach example
In the following example you can see data that was sent via the Emarsys trigger external event API. The foreach
loop will use this data to iterate through and display the products. This data is here to showcase how a payload would look like coming from the API, and this is something that you will need to set up when you create the external trigger. The actual ESL that you can use in your campaigns is in the second half of this example
This is the data that was sent to Emarsys:
{
"key_id": "3",
"external_id": "king@north.com",
"data": {
"customer": {
"id": "1111",
"repId": "1111",
"firstName": "John",
"lastName": "Snow",
"email": "king@north.com",
"phone": ""
},
"order": {
"shipping": "UPS",
"shippingPrice": "5",
"tax": "5",
"subtotal": "50",
"total": "60",
"product_details": [
{
"title": "Product1",
"price": "20",
"quantity": "2"
},
{
"title": "Product2",
"price": "5",
"quantity": "1"
},
{
"title": "Product3",
"price": "5",
"quantity": "1"
}
]
}
}
}
To display products from the data above, we need to use the following foreach
loop:
{% foreach item in event.order.product_details %}
Title: {{item.title}}<br>
Price: ${{item.price|number_format('2', '.', ',')}}
Quantity: {{item.quantity}}
{% endforeach %}