What is Template Engine?

Template Engines are used to manage static files with minimal code and more features. Template Engines use variables, expressions, functions, loops etc which are transformed into HTML Template. We can also include and extends others static files into to manage them easily.

Template Engine
Template Engine

Popular Template Engines

Here is a comparison of top popular Template Engines, with Features, Performance, Popularity and other details.

EJS Vs Mustache Vs Nunjucks Vs Pug( jade)
ejs mustache nunjucks pug ( earlier jade)
Description Embedded JavaScript templates Logic-less templates with JavaScript A rich and powerful templating language for JavaScript by Mozilla A clean, whitespace-sensitive template language for writing HTML
Licenses Apache MIT BSD-2-Clause MIT
Created Feb 2011 Jan 2012 Aug 2012 Aug 2013
Total Versions 66 35 55 31
Dependecies 0 0 4 8
Weekly Downloads 6,115,876 1,517,791 250,308 844,657
Maintainers 1 5 5 2
Github 4.3K 13.8K 6.6K 19.1K
Github 484 2.3K 571 1.9K
Unpacked Size 119 KB 110 KB 1.73 KB 59.4 KB
CLI Shortcut npm i ejs npm i mustache npm i nunjucks npm i pug

The choice of selection of Template Engine depends on requirement.


Install Template Engine

To install template engine, use npm i templatename in terminal. This will install template engine and its dependencies from npmjs.org.

Install EJS

npm i ejs

Install Nunjucks

npm i nunjucks

Install Mustache

npm i mustache

Install Pug

npm i pug


Configure Template Engine

After installing a template engine, the next step is to configure template engine with express.

The configuration on template engine completely depends on him. Please refer to official Github page or docs for more information regarding particular template engine

Configure EJS

Build a index.ejs file for static html page in views folder in src folder of root directory.


const express=require("express");
const path=require("path");
const ejs=require("ejs");
const app=express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.static(path.resolve(__dirname,'assets')));

app.get("/",(req,res)=>{
    res.render('index',{});
});

app.listen(3000,()=>{
    console.log("express server running on ", 3000)
})
    

Configure Nunjucks

Build a index.html file for static html page in views folder of src folder in root directory.


const express=require("express");
const path=require("path");
const nunjucks=require("nunjucks");
const app=express();

app.use(express.static(path.resolve(__dirname,'assets')));

nunjucks.configure(path.resolve(__dirname,'views'),{
    express:app,
    autoscape:true,
    noCache:false,
    watch:true
}); 

app.get("/",(req,res)=>{
    res.render('index.html',{});
});

app.listen(3000,()=>{
    console.log("express server running on ", 3000)
})