To render a basic HTML view in an Express app, we can install a templating library that works with Express.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.get("/", (req, res) => {
res.render('about.html');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
to add the ejs
library by installing:
npm i ejs
Then we write:
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
to serve the views
folder to serve that has the template folder.
We specify that we use the ejs
templating engine with the last 2 lines.
Then in the /
route, we call res.render
with 'about.html'
to serve the content of that as the template.
In about.html
, we have:
about
as its content.
And so when we go to /
, we see about
displayed.