Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Template Engine
3.
Setting the Environment
3.1.
Integrating Express Template Engine
4.
Pug Template Engine
4.1.
Using Partials in Pug
5.
Frequently asked questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Using Template Engine with Express

Author Manvi Chaddha
0 upvote

Introduction

Express is a minimal and flexible Node.js web application framework that provides robust features for web and mobile applications. Several popular Node.js frameworks, including Feathers, ItemsAPI, Blueprint, are built on Express. The main advantage of using Express is that it's very flexible and pluggable, in addition to the numerous modules available on npm, which can be directly plugged into Express.

In this blog, we will look at one of the most important concepts in Express.js: using the template engine with Express.

Template Engine

The dynamic websites or web applications are rendered using a server. You can also render static websites from a server, but it comes with a few limitations like code duplication and lack of flexibility when reading data from a database.

We can use Express.js Template Engine to create dynamic web pages from our server-side application. The flow is as follows: 

  1. You create a template following the appropriate syntax.
  2. Pass variables to it.
  3. Assign values to the variables declared in the template file at the appropriate route to render the template.
  4. This is compiled in run time as the template gets rendered.

In addition, we can also create reusable components called partials which helps to prevent code duplication, and changes are easier to implement.

Thus to formally define a Template Engine, A template engine enables you to use static template files in your application. The template engine replaces variables in a template file with actual values at runtime and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.

Some popular template engines that work with Express.js are enlisted below:

  • Pug (formerly known as jade)
  • mustache
  • dust
  • atpl
  • eco
  • ect
  • ejs
  • haml

In this blog, we will look at Pug, EJS, and Handlebars template engine.

Setting the Environment

Assuming you have node and npm installed, execute the following commands to set up a new npm project and install Express.

npm init

npm i express

 

Create a src folder and a views folder, all the code will be written inside the src folder, and the views folder will hold the views we'll render through express.. Create a new file named app.js inside the src folder, create subfolder partials inside the views folder. The folder structure will look like this:

Now add the following Express boilerplate code to the app.js file.

const express = require("express");
const path = require("path");
const app = express();
app.get("/", (request, response) => {
  return response.send("OK");
});
app.listen(3000, () => {
  console.log("App is listening on port 5000");
});

If everything went well, you have successfully done the basic setup required to proceed with the tutorial. Now let's see how to integrate the Express template engine.

Integrating Express Template Engine

Integrating a template engine into your Express application is quite simple; all you have to do is, Just after assigning the Express function (before creating your routes), add the following app settings:

  • Views: It specifies the directory where the template files are located 

For example app.set('views', './views')) defaults to the views directory in the application root directory

  • view engine: It defines the template engine that you use.

 For example, to use the Pug template engine: app.set('view engine', 'pug').

Then install the corresponding template engine npm package, for example, to install Pug:

npm install pug --save

Pug Template Engine

Let's learn how to use the pug template engine in Node.js application using Express.js. Pug is a template engine for Node.js. Its syntax is quite distinct, favoring indentation spaces over traditional angular brackets in HTML tags. A typical example with head and body segments looks like this:

doctype html
html
    head
        meta(name='viewport', content='width=device-width')
        link(rel="stylesheet", href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css")
        title= subject
    body
        div.container.mt-2
            header
                h2 Welcome
                p  Here is the homepage for #{name}
            section
                h2 Here is the body
                p Lorem ipsum dolor sit, amet consectetur adipisicing elit. Totam, repellendus!
            footer
                h2 Here is the footer
                p
                    a(href=link) Unsubscribe

There are no opening or closing tags, the enclosing tag is declared and its children are indented just below it. Copy the above code into an index.pug file inside the views folder and in the app.js file register Pug as the preferred template engine. Also create a route that renders the file:

app.get("/index", (request, response) => {
  response.render("index", {
    subject: "Pug template engine",
    name: "our template",
    link: "https://google.com",
  });
});

Note that the render method takes the name of the file and the values of the variables, subject, name, and link in this example. Now let's see how to use Partials in Pug. 

Using Partials in Pug

In the partial subfolder create a reusable nav file named as _nav.pug. Its a good practice to prepend partials with an underscore. The contents of the file is given below:

nav.navbar.navbar-dark.bg-primary.navbar-expand
    .container
        a.navbar-brand(href='#') TMP
        ul.navbar-nav.mr-auto
            li.nav-item
                a.nav-link(href='#')
                    span Home
            li.nav-item
                a.nav-link(href='#')
                    span About
            li.nav-item
                a.nav-link(href='#')
                    span Menu
            li.nav-item
                a.nav-link(href='#')
                    span Contact
        span.navbar-text
            a.nav-link(href='#')
                span  Login

The above file might seem a bit confusing for you at first sight. It's simple HTML; the only difference is the absence of opening and closing tags; classes are declared with . and ids are declared with #. Go through it once more, you will understand it now.

Include the partial in index.pug file using the include keyword inside the body tag as shown below:

doctype html
html
    head
        meta(name='viewport', content='width=device-width')
        link(rel="stylesheet", href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css")
        title= subject
    body
        include  partials/_nav  // partial included here
        div.container.mt-2
            header
                h2 Welcome
                p  Here is the homepage for #{name}
            section
                h2 Here is the body
                p Lorem ipsum dolor sit, amet consectetur adipisicing elit. Totam, repellendus!
            footer
                h2 Here is the footer
                p
                    a(href=link) Unsubscribe
                   

Visit the localhost:3000/index, and you should get something like above.

You can learn more from the official pug website. There are other popular template engines that work with Express; they are left for you to explore and learn while practicing.

Frequently asked questions

Q1) What is an Express Template Engine?
Ans 1) A template engine enables you to use static template files in your application. The template engine replaces variables in a template file with actual values at runtime and transforms the template into an HTML file sent to the client.

Q2) Give some examples of Express Template Engines?
Ans 2) Some examples of Express Template Engine are Pug, mustache, dust, atpl, and ejs.

Key Takeaways

This blog discussed Template Engine with Express. With this done, you may learn more about the Basics of JavaScript and Node.js from our Guided Paths.

Developers, if you are preparing for the next interview, check out the blogs 15 Most Frequently Asked React JS Interview Questions and 10 Best ReactJS Interview Questions. And if you are a beginner, check out the Top 5 skills to learn before starting with ReactJs to know the prerequisites to learn React.

We hope you found this blog useful. Feel free to let us know your thoughts in the comments section.

Live masterclass