Search code examples
node.jstypescripthandlebars.js

Is it possible to store handlebars templates in variables, and not in files?


There is a code written in typescript and node.js, the main purpose of it is sending emails. There are email text templates written in handlebars templating language, they are in a folder named "templates" together with the rest of the code.

I want to develop this by let the users edit the email templates. What was in the .handlebars files, now those texts are in the database (users can write it).

Until now, if a trigger happend and the code wanted to send an email, it used something.handlebars as an email text template. But now, the goal would be that the file named something.handlebars wouldn't exist anymore, and I would send what is stored in a given variable.

That variable is filled from the database (this is done), it is a string written in handlebars language. It would be important that handlebars should "process" the content of the variable before sending the email, because the text contains variable substitutions, formatting, etc...

I am not sure if this is possible with handlebars. When I configure handlebars in the code, I have to define a folder which contains the handlebars files, which tells me that I should have handlebars files, not variables which contains text written in handlebars syntax.

Is it possible with handlebars?

If so, how should I configure handlebars, and how could I do this?

If not, could you suggest me another email templating system, which is able to do these things (I mean, load template text from a variable, not a file)?

The current setup is working correctly (using .handlebars files), it sends the emails correctly. But as I see the config of the handlebars system, I guess that it is not possible to load the template text from a variable.


Solution

  • It's very much possible in Handlebars. I don't have your code available or exactly what you want to do, but it's rather simple.

    Let's say you have string like:

    <div>Hello {{name}}</div>
    

    which you have fetched from your database. Then you can simply use:

    const template = Handlebars.compile('<div>Hello {{name}}</div>')
    

    to compile it into a usable HBS template, and send it using that.

    A full tutorial for sending emails with Handlebars can be found here, however, you do need to configure all the basics. But all in all, you can simply compile a string to use it as an HBS template.