This article demonstrates how to use conditional logic in Iterable templates. Find more information in the Personalizing Templates with Handlebars article.
In this article
Display a dynamic-length array in a table with rotating background colors
The example code below uses the following Handlebars helpers to display a
dynamic table that displays the names of a user's cats, as pulled from a cats
array on their user profile:
<table cellpadding="4" cellspacing="1" width="150px"> <thead> <tr> <th scope="col" style="background-color:#000099; color:#FFFFFF">Cat Names</th> </tr> </thead> <tbody> {{#ifGt cats.size 1}} {{#each cats}} {{#ifModEq @index 2 0}} <tr style="background-color:#0099CC; color:#FFFFFF"> <td> {{name}} </td> </tr> {{else}} <tr style="background-color:#FFFFFF; color:#000000"> <td> {{name}} </td> </tr> {{/ifModEq}} {{/each}} {{else}} {{#ifEq cats.size 1}} <tr style="background-color:#FFFFFF; color:#000000"> <td> {{cats.[0].name}} </td> </tr> {{/ifEq}} {{/ifGt}} </tbody> </table>
Examples
The following JSON will generate the preview below:
{ "cats": [{ "name": "Biscuit" }, { "name": "Lucifer" }, { "name": "Arya" }] }
Another example:
{ "cats": [{ "name": "Biscuit" }] }
Check two optional fields for a value
This example assumes that a user profile contains a value for one of two
fields: selected_city
or city
. To check if either of these fields is set
to New York
, use defaultIfEmpty
:
If selected_city
has a value, defaultIfEmpty
returns it; otherwise, it
returns the value of city
. This value is then compared against the string
"New York"
.
Randomly display one of three values
This example outputs one of three values for a subject line, depending on the send time (in seconds). Because send time will vary based on trigger time and processing time, this approach should lead to a nearly even distribution of subject line alternatives.
NOTE
To measure differences in engagement across variations, use an experiment instead of the method described here. This method does not record the variation used at send time.
Display a fallback value if a user profile field is empty
No matter how good your data is, sometimes you'll be missing information about some of your users — which can make it tricky to send personalized messages. To avoid sending messages with blank fields, you can add fallback values that will display when a user profile field is empty:
Want to learn more?
For more information about some of the topics in this article, check out this Iterable Academy course. Iterable Academy is open to everyone — you don't need to be an Iterable customer!