InsightConnect and the Oxford Comma Problem

So, you’ve built this absolutely amazing workflow and it generates an array of users it blocked. Now you want to send an e-mail with a nice, human style list of these users.

For example:
Hi team,
ICON just blocked Jon, Mike, and Luke because they all tried to login from the same address.
Sincerely,
InsightConnect

But how do we do this? With handlebars we can easily create a list with one item per line:
{{#each [“ourobject”].[array]}}
{{this}}{{/each}}
becomes
Jon
Mike
Luke

or all on one line:
{{#each [“ourobject”].[array]}}{{this}} {{/each}} -> Jon Mike Luke

Or even with commas after each entry:
{{#each [“ourobject”].[array]}}{{this}}, {{/each}} -> Jon, Mike, Luke,

Our last one looks pretty close - we’ve just got an extra comma after Luke and we’re missing the ‘and’

The missing piece is done with handlebars array index magic and the #if and #unless helpers!

{{#each [“ourobject”].[array]}}{{#if @last}}and {{/if}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}
becomes
Jon, Mike, and Luke

What happens when we only have two items in the list?
Jon, and Mike

NOOOO, the oxford comma doesn’t apply for only two item lists!

So let’s try again:
{{#each [“ourobject”].[array]}}{{#unless @first}}{{#unless @last}}, {{/unless}}{{/unless}}{{#if @last}}{{#unless @first}} and {{/unless}}{{/if}}{{this}}{{/each}}
becomes
Jon and Mike

but with 3 in the list, we now lose the oxford comma!

Unfortunately, to get the oxford comma we need a second artifact that’ll tell us if we’re in a 2-item list.

Our new artifact is just called length and it contains this:
{{#each [“ourobject”].[array]}}{{#if @last}}{{#equal @index 1}}1{{/equal}}{{/if}}{{/each}}
What this does is renders a 1 if the length of our array is 2 elements long and empty otherwise. We’re going to use this in our oxford comma string to turn off the comma on a 2 element long array.

So, to get the full oxford comma treatment, here’s our final handlebars:
{{#each [“ourobject”].[array]}}{{#unless @first}}{{#unless [“length”].[content]}}, {{#if @last}}and {{/if}}{{else}} and {{/unless}}{{/unless}}{{this}}{{/each}}
becomes
(1 name) Jon
(2 names) Jon and Mike
(3 names) Jon, Mike, and Luke
(4 names) Jon, Mike, Luke, and Zac

So here’s our email, with a fully dynamic oxford comma following all the rules:
Hi team,
ICON just blocked {{#each [“ourobject”].[array]}}{{#unless @first}}{{#unless [“length”].[content]}}, {{#if @last}}and {{/if}}{{else}} and {{/unless}}{{/unless}}{{this}}{{/each}} because they all tried to login from the same address.
Sincerely,
InsightConnect

2 Likes