The post ExpressJS Template Engines Introduction gives an introduction to template engines that can be used with Express.js. In this article we'll see how to use EJS template engine.
Installing EJS
You can install EJS by using the following command.
npm install ejs
Settings in Express.js for using EJS
You need to configure EJS as the view engine in Express.js app.
app.set('views', './views')
This setting sets the views directory in the application root directory as the location where template files are saved. Template engine will search this directory to locate the template that has to be transformed. By default template engine searches in 'views' directory so you can omit this configuration if you are saving template files in 'views' directory.
app.set('view engine', 'ejs')
This setting sets EJS as the template engine.
Writing EJS template
You can use express-generator to create project structure which gives a views directory and with in that folder you can create files with .ejs extension.
EJS templates are very similar to HTML only difference is the use of template tags <% %> to produce dynamic content.
views\home.ejs
<!DOCTYPE html> <html> <head> <title><%= pageTitle %></title> </head> <body> <h1>EJS Demo</h1> <p>Welcome <strong><%= userName %></strong></p> </body> </html>
As you can see template tags are used at two places with in the template.
<title><%= pageTitle %></title> <p>Welcome <strong><%= userName %></strong></p>
app.js
const express = require('express'); const app = express(); const port = 3000; const path = require('path'); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.get('/', (req, res) => { res.render('home', {pageTitle:'HomePage', userName:'TestUser'}); })
Some important points to note here-
- Properties are set for template engine using app.set() method.
- In res.render() method template name is passed as the first parameter and as a second parameter an object is passed which has values set for the variables in the template with variable name as key.
This is the generated HTML that you can view by going to page source.
<!DOCTYPE html> <html> <head> <title>HomePage</title> </head> <body> <h1>EJS Demo</h1> <p>Welcome <strong>TestUser</strong></p> </body> </html>
That's all for the topic ExpressJS: EJS Template Engine Integration With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- ExpressJS: Pug Template Iteration Examples
- ExpressJS: Pug Template Inheritance
- ExpressJS Query Parameters
- Using express-generator to Create ExpressJS App Structure
- Express res.sendFile() Method With Examples
- Synchronized Vs ReentrantLock in Java
- Exception Propagation in Java
- Password Protected PDF Using PDFBox in Java
- HTTP DELETE Method in React - fetch, Axios
- Spring Bean Lifecycle Callback Methods
No comments:
Post a Comment