Using the Handlebars templates with SendGridForEpi

SendGrid has marked Substitutions as Legacy and switched to Handlebars for the transactional templates.

I'm pretty sure you've checked out the Handlebars.js syntax and know that it's a powerful way to insert data into a template. This is very welcome since for example looping stuff in a typical SendGrid template case such as an order confirmation was a bit of a hassle before, often having to construct a big chunk of HTML as the likely option.

So... When using it from C# it's best to forget about the old substitution variable way and instead think view model. In this very simple example I need two string properties where one will get an HTML value set.

private class CommentTemplateData
    public string WhoIs { get; set; }

    public string CommentText { get; set; }

I put some JsonProperty-decorations in there to not offend anyone working with JS with improper name casing.

To avoid getting the markup in commentText escaped I need to "triple-stash" that property in the SendGrid template.

Then to wrap it up when sending through SendGridForEpi I use the TemplateData property found on the regular SendGrid Personalization object.

var mail = new SendGridMessage
    From = new EmailAddress(""),
    TemplateId = "the-id-found-in-the-sendgrid-template-editor",
    Personalizations = new List<Personalization>()

    new Personalization()
        Tos = new List<EmailAddress>
          new EmailAddress("")
            TemplateData = new CommentTemplateData
            WhoIs = "Some Name",
            CommentText = 
              "<p>First line of comment.</p><p>Second line of comment.</p>",

this.mailService.AddToQueue(new MailQueueItem
    Date = DateTime.UtcNow,
    Mail = mail

This support was added in the official C# library with 9.10 released 2018-09-12. The SendGridForEpi package dependent on this version as a minimum is 1.2.2 which will be up on Epi's NuGet feed shortly.

Check the package source code on Github or the initial blog post if you missed the SendGridForEpi introduction.

Published Monday 19 November 2018 21:00 and tagged with these categories: Episerver, ASP.NET


Add Your Comment