For example, you might want to have components such as body, navigation, footer, dashboard, etc.
The following steps demonstrate how template engines work using expressJs
and the ejs
template engine. The example given below renders a user’s data on the web page.
npm install express ejs
const express = require("express")const app = express();// Set the View Engine or Template Engineapp.set('view engine', 'ejs');app.listen(3000)
In the code above, we created our express application. The application listens on port 3000
.
This line of code: app.set('view engine', 'ejs')
, tells our express application that we want to use EJS as our template engine.
app.get('/', function (req, res) {res.render("index");})app.get("/user", function(req,res){const user = {name: "Theodore Kelechukwu O.",stack: "MERN",email: "theodoreonyejiaku@gmail.com",hubby: ["singing", "playing guitar", "reading", "philosoph"]}res.render("user", {user});})
As we have seen, the default route “\”, when accessed, displays or renders the index.ejs
page. Meanwhile, the “\user” renders the user.ejs
page.
We passed the user
object to the render object so as to pass the user
properties to the web page and render it.
<html><head><title>This is the title</title></head><body><h1>Welcome to User Details</h1><p><b>Name:</b> <%= user.name %></p><p><b>Email:</b> <%= user.email %></p><p><b>Stack:</b> <%= user.stack %></p><u><b>Hubbies</b></u><% user.hubby.forEach(hubby =>{ %><li><%= hubby %></li><% })%></body></html>
Note the <%= variable %>
pattern of displaying values. That is the way it is used in ejs
. Also notice the user.forEach()
; this is to show how powerful template engines can be.
You can view the live app here:
You can view the full source codes here:
Thanks for reading. I hope you now have a better understanding of template engines. Personally, I have used Express Handlebars
and EJS
, but I prefer EJS
.