Send fetched strings with Handlebars by compiling

February 26, 2023

Mail

In this series on handlebars and emails, we’ve gone through how to send basic emails using Handlebars email, and now, we’ll further improve this. You can check out the other two posts here and here.

Prequisites

  • Code used in earlier post

What is Handlebars.js?

As we’ve explained earlier, Handlebars.js pretty much only extends Mustache templating language, and is mostly used for sending more advanced emails from your node backend. And it’s super easy to use, so let’s get started.

Fetching an HTML string

Let’s say you have a backend database that contains your HTML templates for sending emails. This could be for example if you have not-so-technical persons editing the email templates, without you having to store them in the code.

This could for example return a simple string like this:

<div>Welcome {{ name }}! I was fetched from a database!</div>

In this case, name is a variable that can be changed depending on the context.

Compiling a string into HBS HTML

Now, we cannot use this string directly, due to the fact that in that case it would only be sent as a string, and we wouldn’t get the benefits of having variables in it, so in this case, we need to compile it into HBS.

So let’s say we have an endpoint like this:

app.post('/send-email-from-fetched-template', async (req, res) => {
    try {
        transporter.sendMail({
            from: 'Anonymous Coder<anonymous@coder.com>',
            to: 'random@coder.com',
            subject: 'Your email',
            html: '<div>Welcome {{ name }}! I was fetched from a database!</div>',
        }, (what) => {
            res.status(200).send('Email sent')
        })
    } catch {
        return res.status(400).send('Email not sent')
    }
})

As I said, this won’t work as it should, we need to add one simple line to make it perfect:

const template = Handlebars.compile('<div>Welcome {{ name }}! I was fetched from a database!</div>')

In the end, we will end up like this:

app.post('/send-email-from-fetched-template', async (req, res) => {
    const template = Handlebars.compile('<div>Welcome {{ name }}! I was fetched from a database!</div>')
    try {
        transporter.sendMail({
            from: 'Anonymous Coder<anonymous@coder.com>',
            to: 'random@coder.com',
            subject: 'Your email',
            html: template({name: 'Anonymous coder'}),
        }, (what) => {
            res.status(200).send('Email sent')
        })
    } catch {
        return res.status(400).send('Email not sent')
    }
})

Wrap-up

In this post, we’ve gone through how you can use Handlebars.js and your own HTML string to compile it into a HBS template that can be sent with variables.


Profile picture

Written by An anonymous coder who lives and works building useful things. Mostly focusing on Django, Vue and overall Python examples.