JavaScript

Express.js Template Engine

Hello. In this tutorial, we will understand how to a template engine in a simple express.js application.

1. Introduction

The template engine in the express js application helps to use the static template files in the applications. At runtime, it replaces the variable in the template file with the actual values. Some of the commonly used popular template engines are – Jade, mustache, dust, atpl, etc. In this tutorial, we will use the jade template engine for implementation.

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

2. Express.js Template Engine

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

Let us take a look at the code structure.

Fig. 2: Application code structure

2.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Replace the generated file with the code given below –

package.json

{
  "name": "expressjs-templateengine",
  "version": "1.0.0",
  "description": "Jade template engine in node.js application using express.js",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js",
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "jade",
    "node",
    "express",
    "expressjs-templateengine",
    "templateengine"
  ],
  "author": "geeks",
  "license": "MIT",
  "dependencies": {
    "express": "^4.17.3",
    "jade": "^1.11.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

Once the file is replaced trigger the below npm command in the terminal window to download the different packages required for this tutorial.

Downloading dependencies

npm install

2.2 Creating templates

By default, expressjs searches for all the view pages in the views folder under the project root. However, in this tutorial, we will change this default behavior by moving all the view pages to the pages folder.

2.2.1 Welcome page

Create a file named – welcome.jade responsible to show the welcome page to the user when the / endpoint is hit in the browser.

welcome.jade

doctype html
html
    head
        title Jade Page
    body
        h3 This page is produced by Jade engine
        p Hello world

2.2.2 Employees page

Create a file named – employees.jade responsible to show the employee list by fetching the data from the mock sql table. The page will be shown to the user when the /sql endpoint is hit in the browser.

employees.jade

doctype html
html
  head
      title Employees
  body
      h3 List using Jade engine
      ul
        each item in employeeList
            li=item.name

2.3 Setting up the implementation file

Create a file responsible to describe the implementation. The file will be responsible to perform three different things –

  • Expose the application endpoints
  • Override the default folder name for the views
  • Setting the view engine to jade

index.js

const express = require("express");

// setting up express server
const app = express();

// setting the view folder for the jade files
app.set("views", "pages");
// setting app engine
app.set("view engine", "jade");

// -- application endpoints --

// http://localhost:3005
app.get("/", (req, res) => {
  res.render("welcome");
});

// http://localhost:3005/sql
app.get("/sql", (req, res) => {
  const records = [
    {
      id: "101",
      name: "Jane Doe"
    },
    {
      id: "102",
      name: "Neil Irani"
    },
    {
      id: "103",
      name: "Tom Hanks"
    }
  ];
  res.render("employees", { employeeList: records });
});

// driver code
const SERVER_PORT = 3005;
app.listen(SERVER_PORT, () => {
  console.log(`Service endpoint = http://localhost:${SERVER_PORT}`);
});

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run dev

If everything goes well the application will be started successfully at the service endpoint – http://localhost:3005

4. Application endpoints

The application exposes the below endpoints that you can explore in the browser to understand the jade implementation.

Application endpoints

// application endpoint

// http get - http://localhost:3005

// http get - http://localhost:3005/sql

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we saw the jade implementation in an expressjs application. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to implement jade in a nodejs and express application.

Download
You can download the full source code of this example here: Express.js Template Engine

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button