Template engines are powerful solutions to use static template files to render dynamic data on the server side and return HTML pages to the client.
Most popular template engines work out of the box with Express.js(Link)
In this section, I’ll only introduce Ejs and Pub which I think are two of the most popular.
First of all, template engines have their syntax, most of the time similar to HTML and some of them let us write vanilla JS codes to handle the dynamic data easily within the templates. In the end, we write our code based on the engine that we pick, telling Express to handle which template engine we use and it transforms the code and returns a pure HTML file to the client.
In our main server/app.js file, we should let Express know which template engine we are going to use by using set method that comes natively with Express.js.
What is set method?
set method comes with Express and lets us set up global settings for our Express app. It takes two arguments, the first one is the name of the setting and the second one is the value of that setting.
server.js
const path = require("path");
const express = require("express");
const app = express();
app.set("view engine", "ejs"); // for the ejs
// or
app.set("view engine", "pug"); // for the pug
app.set("views", "views"); // this is the default path for our template engine files but we can define a different path if we like
const postRoute = require("./routes/post");
app.use("/posts", postRoute);
app.use((req, res, next) => {
res.status(404).render("404", { pageTitle: "Page Not Found" }); // this will look for 404.ejs or 404.pug file based on the engine setting that we provide inside the views folder, also pageTitle is the dynamic value and we should provide it to our file
});
app.listen(3000);
404.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<meta
http-equiv="X-UA-Compatible"
content="ie=edge"
/>
<title><%= pageTitle %></title>
<link
rel="stylesheet"
href="/css/main.css"
/>
</head>
<body>
<header class="main-header">
<nav>
<ul>
<li><a href="/">Homepage</a></li>
<li>
<a href="/posts/add-post">Add Post</a>
</li>
</ul>
</nav>
</header>
<h1>Page Not Found!</h1>
</body>
</html>
404.pug
doctype html
html(lang="en")
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title #{pageTitle}
link(rel="stylesheet", href="/css/main.css")
body
header.main-header
nav.main-header__nav
ul.main-header__item-list
li.main-header__item
a(href="/", class=(path==='/' ? 'active' : '')) Shop
li.main-header__item
a(href="/posts/add-post", class=(path==='/posts/add-post' ? 'active' : '')) Add Post
h1 Page Not Found!