In our second blog on using placeholders with the Emarsys API, we will look at using a foreach loop to pull data from an array.

Use case

You want to trigger a standard email response to a purchase, listing the products bought. But you don’t know how many products there will be, so you need a dynamic section in the email that can repeat as many times as there are products to list.  

For this, we can use aarray to store all the products bought, and a foreach loop to process the dataThe foreach loop will perform the same action on every entry in the array, until there is no more data to display.  

The way this works for the API is that we declare an array in the JSON, and use a foreach loop to loop through all the different things in the array.  

Here is an example of the HTML of our email: 

<html>  
 <head>  
  <title>API Exercise 2 Example</title>  
 </head>  
 <body>  
  <h2>Exercise 2 - For Each Loop</h2>  
  <p>  
   Dear {{event.firstName}},<br>  
   Please find your order details below:  
  </p>  
 {% foreach item in event.orderDetails %}  
  <ul>  
   <li>Ordernumber: {{item.orderNumber}}</li>  
   <li>Product: {{item.productName}}</li>  
   <li>Quantity: {{item.Quantity}}</li>  
   <li>Price: {{item.Price}}</li>  
  </ul>  
 {% endforeach %}  
 </body>  
</html> 

We can see that the first name of the user is a regular placeholder, defined by {{event.firstName}}. 

Then the foreach statement starts. The syntax is slightly different here from a usual placeholder. Instead of double curly brackets, we now use one curly bracket and one percentage character. 

I find the difference between when to use {{ }} and when to use {% %} easiest explained by: 

    • {{ say something }} (like personalization) 

 

    • {% do something %} (like an IF statement or a foreach loop) 

Let’s look at the architecture of the foreach statement for a moment. 

    • {% foreach opens the foreach statement and indicates a loop is about to start

 

    • item is the key that is used for the array that is about to be defined

 

    • in Indicates that we are looking for each entry of the key called item, inside the array

 

    • event. is the key used for the JSON body. As the array itself is part of the JSON body, it must be prefixed with event.’.

 

    • orderDetails is the name of the array

 

    • endforeach %} closes the foreach statement 

Each entry of the array must be prefixed with the key of the array, which can be anything. In this example we have declared the array’s key as item, which is why you see item. before each entry that is part of the array. 

The array itself is part of the JSON body, which is why it must be prefixed using event., which is the pre-defined key for any JSON objects that are part of the JSON object itself. 

We can now pass multiple objects through the JSON, and the foreach loop will display each object inside the array. Here is an example we could use: 

{ 
  "key_id": "3",  
  "contacts":  
  [  
    {  
      "external_id": "elston.gunn@example.com",  
      "data":  
      {  
        "firstName": "Elston",  
        "orderDetails":  
        [  
    {  
            "orderNumber": 1223456,  
            "Product": "Football",  
            "Quantity": "1",  
            "Price": "€25,-"  
           },  
           {  
             "orderNumber": 27346575,  
             "Product": "Garden Furniture Set",  
             "Quantity": "1",  
             "Price": "€685.95"  
           }  
        ]  
      }  
    },  
    {  
      "external_id": "tedham.porterhouse@example.com",  
      "data":  
  {  
          "firstName": "Tedham",  
          "orderDetails":  
            [  
              {  
                "orderNumber": 1223456,  
                "Product": "Vacuum Cleaner",  
                "Quantity": "1",  
                "Price": "€85.95"  
              },  
              {  
                "orderNumber": 27346575,  
                "Product": "Washing Tabs",  
                "Quantity": "3",  
                "Price": "€15,-"  
              }  
            ]  
        }  
    }  
  ]  
} 

To add an extra layer of complexity, we’ve assumed multiple contacts using the same account. This means the above example needs to use an array within an array (we call this a multi-dimensional array). One array indicates the contacts (recipients) and the other array indicates the order details that go with each contact. In this way we can list both multiple contacts and multiple orders for each of them. 

Let’s look at what is going on in detail: 

    • The first curly bracket { at the top opens the JSON object

 

    • key_id is defined as the email address

 

    • We use the key-word contacts to indicate that more than one contact is going to be used in this payload

 

    • The square bracket [ opens the array, which we need because the order details will contain multiple items

 

    • The second curly bracket { opens the object for the recipient. Here, we declare the first contact

 

    • external_id is the contact identifier (defined above as the email address)

 

    • We now declare the data object, which contains any placeholders that are not part of the array, in this case the user’s first name. It is not an array, as it’s a single value

 

    • orderDetails is the name of the array, and we open it using an opening square bracket [

 

    • We now open the first object inside the array using an opening curly bracke{

 

    • Next, we declare all the variables that contain the values of the placeholders we are using inside the orderDetails array. We close this with another curly bracket }

 

    • The second object is declared inside the array, also enclosed in curly brackets { }

 

    • We close the array with a square bracket ], as that’s all for this particular user

 

    • We also close the data and external_id objects for this recipient with two more curly brackets }

 

    • And finally, we repeat the external_id and data objects for the second recipient

Triggering this will trigger two emails, one to each recipient, with their respective order details populated in the section you have defined, for example:

Dear Elston,

Please find your order details below:

    • Order number: 1223456

 

    • Product: Football

 

    • Quantity: 1

 

    • Price: €25

 

    • Order number: 27346575 

 

    • Product: Garden furniture set

 

    • Quantity: 1

 

    • Price: €685.95

One added benefit of this method is that since these two emails are triggered in one API call, you can send more traffic through the API without hitting the rate limit (default limit is 1,000 calls per minute).

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x