"Else equals" in Handlebars (in SendGrid's Dynamic Templates)
Published on in Handlebars and SendGrid
There's a way to do an "else equals" check in Handlebars (in SendGrid's Dynamic Templates), though it's undocumented and a bit tricky.
Table of contents
Context
Problem
I wanted to do something like this:
<h1>New article: </h1>
<h1>Ny artikel: </h1>
<h1>Uusi artikkeli: </h1>
But it wasn't quite that simple.
Solution
Step by step
- Handlebar's
#ifhelper checks only the truthiness of a value; you can't use==or other operators, so{{#if locale == 'en'}}is invalid. - You can create custom Handlebars helpers. However, when using Handlebars in SendGrid, you are limited to SendGrid's Handlebars helpers.
- Luckily
SendGrid provides an
#equalshelper:<h1>New article: </h1> <h1>Uusi artikkeli: </h1> - But whoops,
Handlebars helpers create new scopes,
so
{{articleNameEn}}and{{articleNameFi}}are "empty." Need to use the@rootkeyword: - And how to do "else equals"?
The documentation doesn't tell.
But "else if" is documented,
so let's try to imitate that:
This code is syntactically valid and almost works:<h1>New article: </h1> <h1>Ny artikel: </h1> <h1>Uusi artikkeli: </h1>- If
localeis'en', the first branch is executed. - But if
localeis'sv', the third branch is executed. So the second branch ("else equals") is never executed.
- If
- Aha! Same gotcha as above.
Because Handlebars is so eager to create new scopes,
need to use the
@rootkeyword here as well:
Final code
<h1>New article: </h1>
<h1>Ny artikel: </h1>
<h1>Uusi artikkeli: </h1>