• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Building Dynamic Web Applications with Express and EJS: A Step-by-Step Tutorial

  • June 23, 2023
  • CODE OF GEEKS
  • 0
In this Tutorial ->
  • What is EJS?
  • Advantages of EJS Templating Engine
  • Getting Started with EJS Syntax
  • Setting up Express Project
  • Installing EJS
  • Configure EJS as the template engine
  • Create Pug templates
  • Render EJS templates
  • Start the application
Building Dynamic Web Applications with Express and EJS
Building Dynamic Web Applications with Express and EJS

Building dynamic web applications requires a robust framework and a flexible templating engine. In this tutorial, we will explore how to create dynamic web applications using Express, a popular web application framework for Node.js, and EJS (Embedded JavaScript), a powerful templating engine. By the end of this step-by-step tutorial, you will have a solid understanding of how to set up an Express application, integrate EJS, and create dynamic web pages that can interact with data. Let’s get started!

What is EJS?

EJS, short for Embedded JavaScript, is a templating engine for Node.js and browsers that enables developers to generate dynamic HTML markup by combining JavaScript code with HTML. It allows you to embed JavaScript logic and variables directly into your HTML templates, making it easier to create dynamic web pages.

Advantages of EJS Templating Engine

Seamless integration: EJS can be easily integrated into existing projects without the need for major architectural changes.

Familiar syntax: The syntax of EJS closely resembles traditional HTML, making it easier for developers to grasp and use effectively.

Versatility: EJS allows the use of JavaScript code, enabling dynamic content generation and integration with server-side data.

Reusability: EJS supports the creation of reusable templates and partials, reducing code duplication and improving maintainability.

Developer-friendly: EJS provides an intuitive and flexible environment for developers, allowing them to focus on the logic and data manipulation without getting lost in complex syntax.



Getting Started with EJS Syntax

Embedding JavaScript Code: EJS allows you to embed JavaScript code within your HTML templates using the <% %> delimiters. For example:

<ul>
  <% for (let i = 0; i < 5; i++) { %>
    <li><%= i %></li>
  <% } %>
</ul>

Rendering Variables: You can render variables in your templates using the <%= %> delimiters.
For example:

<h1>Welcome, <%= username %>!</h1>

Including Partial Templates: EJS supports the inclusion of partial templates using the <%- include() %> syntax. This allows you to reuse common components across multiple views. For example:

<div class="header">
  <%- include('partials/header') %>
</div>

Conditionals and Loops: EJS provides conditional statements (if, else if, else) and loop structures (for, while) to control the flow of your templates. For example:

<% if (isLoggedIn) { %>
  <h1>Welcome, <%= username %>!</h1>
<% } else { %>
  <h1>Please log in to continue.</h1>
<% } %>

You can pass data to your EJS templates from your server-side code using variables. EJS templates can access and render this data to create dynamic content.



Setting up Express Project

1. Create a new directory for your project and navigate to it in your terminal:

mkdir express-ejs-app
cd express-ejs-app

2. Initialize a new npm project by running the following command and following the prompts:

npm init

3. Install Express as a dependency:

npm install express

4. Create a file named app.js (or any other preferred name) in the project directory. This will be the entry point of your Express application.

5. Open app.js in a code editor and add the following code to set up a basic Express application:

// Import the required modules
const express = require('express');
const app = express();
const port = 3000; // Choose your preferred port number

// Set up a route for the homepage
app.get('/', (req, res) => {
  res.send('Hello, Express!');
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

6. Save the file and go back to your terminal.

7. To start the Express application, run the following command:

node app.js

Once the server is up and running, you will see following message in the console:

‘Server is running on port 3000’

Open your web browser and visit http://localhost:3000 (replace 3000 with the port number you chose in the code). You should see the message “Hello, Express!” displayed in the browser.

Hello Express
Hello Express

You can stop this server by pressing CTRL+C.



Installing EJS

To install EJS in your project, use the following command:

npm install ejs

Configure EJS as the template engine

Open the app.js file located in the root directory of your Express.js application. Add the following lines of code to configure EJS as the template engine:

// Set the 'views' directory for your EJS templates
app.set('views', path.join(__dirname, 'views'));

// Set EJS as the template engine
app.set('view engine', 'ejs');

In the code above, we’re setting the “views” directory as the location where your ejs templates will be stored. Adjust the path as per your project’s structure.

Create Pug templates

Create a new directory called views in the root directory of your application. Inside the views directory, create EJS template files with a .ejs extension. For example, create a file named index.ejs with the following content:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
  </head>
  <body>
    <h1>Welcome to <%= title %></h1>
  </body>
</html>

The <%= title %> syntax is used to render the title variable passed from the server.

Render EJS templates

To render the ejs template, please add the following code in app.js:

app.get('/', (req, res) => {
  res.render('index', { title: 'Express App' });
});

Below is the modified version of app.js:

const express = require('express');
const app = express();
const path = require('path');

// Set the 'views' directory for your EJS templates
app.set('views', path.join(__dirname, 'views'));

// Set EJS as the template engine
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.render('index', { title: 'Express App' });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Start the application

Finally, start your Express.js application by running the following command in your terminal:

node app.js
Express + EJS
Express + EJS

Now, if you visit http://localhost:3000/ in your web browser, you should see the rendered EJS template.

EJS Template
EJS Template

With these steps, you have successfully configured EJS as the template engine in your Express application. Now you can create dynamic web pages using EJS syntax and render them using Express.





Focus Meta Keywords: Express.js, EJS, Templating Engine, Web Application, Node.js, Integration, Configuration, Views, Templates, Routes, Dynamic Web Applications.

Tags: express ejsexpress with ejsnode application with ejs
  • Previous Serving Static Files in Express: A Complete Tutorial
  • Next Building Dynamic Web Applications with Express and Pug: A Step-by-Step Tutorial

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.