This article demonstrates how to use conditional logic in Iterable templates. Find more information in the Personalizing Templates with Handlebars article.
Display a dynamic-length array in a table with rotating background colors
The following example uses
indexing and the
#ifGt
,
#each
,
#ifModEq
and
#ifEq
helpers to
display a dynamic table with a user's cats' names (pulled from a cats
array
on the 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:
Comments
0 comments
Please sign in to leave a comment.