To output dynamic content in Express, we can use view engine or template engine.
With view engines, we can create HTML and insert a bit of JS here and there.
The Express application generator uses Jade as its default, but it also supports several others.
Some popular template engines that work with Express are Pug, Mustache, and EJS.
To install Pug:
$ npm install pug
To install Mustache:
$ npm install mustache --save
To install EJS:
$ npm install ejs
To render template files, we need to set:
If we’d like to set it to something else, we can use app.set()
. It lets us configure some application settings.
app.set("views", "myviews");
app.set("view engine", "ejs");
Below is an example app using EJS.
To install EJS in our Express app, we use npm:
$ npm install ejs
Once we’ve installed EJS, we can register view engine in our Express app.js with app.set()
.
const express = require("express");
// express app
const app = express();
// register view engine
app.set("view engine", "ejs");
Automatically, EJS will look into the “views” folder to find the templates.
To create the views, we use .ejs
extension. For example, in /views folder, we create
EJS uses regular HTML for its templates
<h2>Homepage</h2>
<p>Hello, world</p>
To render a view, we use render()
method. Inside the method, we pass in the template name without the .ejs extension.
const express = require("express");
// express app
const app = express();
// listen for requests
app.listen(3000);
// register view engine
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index");
});
app.get("/about", (req, res) => {
res.render("about");
});
// 404 page
app.use((req, res) => {
res.status(404).render("404");
});
In .ejs template, JavaScript expressions, HTML, and comments have special tags.
Subject | Tags | Description |
---|---|---|
JavaScript expressions | <% (…) %> | The tags define JavaScript operations |
HTML-code | <%= (…) %> | The tags escape HTML-construction |
<%- (…) %> | The tags output information with unescaped buffering | |
Comments | <%# (…) %> | The tags highlight the comments |
Example: We pass titles for each templates
const express = require("express");
// express app
const app = express();
// listen for requests
app.listen(3000);
// register view engine
app.set("view engine", "ejs");
app.get("/", (req, res) => {
res.render("index", { title: "Home" });
});
app.get("/about", (req, res) => {
res.render("about", { title: "About" });
});
// 404 page
app.use((req, res) => {
res.status(404).render("404", { title: "404" });
});
In the <head>
section of each template, we use ejs syntax <%= title %>
to output a variable
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%= title %> | My Blog</title>
</head>