The view layer is the part of the MVC architecture that the user can see, so of course, it should be created with HTML.
1app.get("/", (req, res) => {
2 res.send(`<!DOCTYPE html>
3<html>
4<head>
5 <meta charset="UTF-8" />
6 <title>title</title>
7</head>
8<body>
9 . . .
10</body>
11</html>`);
12});
But, there is a problem, because in practice, we cannot hard code the entire webpage.
For example, what if we need to embed variables inside the HTML template? Or, what if we need to conditionally render a piece of HTML based on certain requirements? Essentially, we need to add some programming features to the static HTML page.
This is why we need a template engine. Think of it as a mini-framework that works inside Express. Its job is to generate a proper HTML page for the view layer based on a template.
Getting started with Pug
The default template engine for Express is Pug, which can be installed with the following command:
1npm install pug --save
Create an index.pug
file inside the views
directory.
1.
2├── controllers
3├── database.sqlite
4├── index.js
5├── models
6│ └── user.js
7├── package-lock.json
8├── package.json
9├── routes
10└── views
11 └── index.pug <===