July 16, 2024

ExpressJS: EJS Template Engine Integration With Examples

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-

  1. Properties are set for template engine using app.set() method.
  2. 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

No comments:

Post a Comment