Hello Friends,
Welcome To Infinitbility!
This article explain and provide example to implement Mustache template in node js. we are assuming you want send mustache template content in your mail function.
Let’s start today topic integrate mustache template in nodejs with typescript
-
Start with Installation
npm install consolidate mustache --save
install consolidate and mustache library to setup mustache render engine
-
Setup mustache engine
app.ts
import
consolidate engine
import engine from "consolidate";
- create private function initializeMailTemplate
private initializeMailTemplate(){ // set templates folder this.app.set('views', __dirname + '/views'); // // set html templating engine this.app.engine('html', engine.mustache); this.app.set('view engine', 'html'); }
- call from constructor
constructor(routes: Routes[]) { this.app = express(); this.initializeMailTemplate(); }
-
use engine in nodejs controler for render template
mails.controller.ts
import { NextFunction, Request, Response } from 'express'; import sendMail from "@utils/sendMail"; class MailsController { /** * Send Mail * * @param req * @param res * @param next */ public emails = async (req: Request, res: Response, next: NextFunction) => { try { const email: string = req.body.email; const template: string = req.body.template; const template_data: object = req.body.template_data; // template will be your template file name res.render(template, template_data, function (err, html) { const msg = { to: email, // Change to your recipient from: process.env.SENT_MAIL_ID, // Change to your verified sender subject: 'Welcome To Infinitbility', html: html, } sendMail(msg); }); res.status(200).json({ message: 'Mail Sent Successfully' }); } catch (error) { next(error); } }; } export default MailsController;
-
Create html template
- create views folder on your src folder and add below registration template
registration.html
<!DOCTYPE html> <html> <body> <p> Hi {{name}}, Thank You For Registration. </p> </body> </html>
Thanks For Reading…