Skip to main content

Command Palette

Search for a command to run...

Using the EJS template in the node.js application

Updated
Using the EJS template in the node.js application
Y

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.

Date: 2022-04-27

Understanding Embedded JavaScript Templating (EJS) in Node.js and Express.js Applications

This article explores Embedded JavaScript Templating (EJS), a powerful tool for creating dynamic web pages within Node.js and Express.js applications. EJS simplifies the process of generating HTML content by allowing developers to embed JavaScript code directly within their HTML templates. This approach eliminates the need for extensive string manipulation or complex logic within the application's main code, leading to cleaner, more maintainable projects.

Before diving into EJS, let's understand the context. Node.js is a JavaScript runtime environment that allows you to execute JavaScript code outside of a web browser. Express.js, built on top of Node.js, is a popular web application framework that provides a robust set of tools for building web servers and handling requests. In a typical web application, the server-side logic (processing data, accessing databases) is separated from the client-side (the user interface displayed in the browser). EJS bridges this gap, allowing server-side data to be seamlessly integrated into the HTML sent to the client.

EJS achieves this integration through a system of special tags. These tags, embedded within the HTML, act as placeholders for data that will be dynamically inserted during the rendering process. The server-side code provides the values for these placeholders, effectively customizing the HTML output for each user request. Imagine creating a personalized greeting – instead of hardcoding names directly into your HTML, you use EJS to insert the user's name based on their session data. This makes the application far more adaptable and efficient. While the specific tags themselves are not described here (refer to the EJS documentation for a complete listing), they operate on the principle of using JavaScript expressions within the template to manipulate and output data.

Setting up a Node.js environment is the first step. This involves downloading and installing the Node.js installer from the official website. The installer typically includes npm (Node Package Manager), a crucial tool for managing project dependencies. After a successful installation, you can verify the installation by opening a command prompt and typing node -v and npm -v which should display the installed versions.

To illustrate EJS in action, let's consider a simple example: building a web application to display student information. This application involves two key files. The first is the EJS template file, typically named with the .ejs extension and stored in a views directory. This template file contains the HTML structure of the page, including EJS tags that act as placeholders for the student data. For instance, the template might contain something like:

"

Student Name: <%- student.name %>

Student ID: <%- student.id %>

"

This indicates that the name and ID values will be pulled from a student object provided by the server-side code. The < -% ... %> syntax demonstrates the basic EJS templating logic.

The second file is the main application file (typically index.js or app.js), responsible for setting up the Express.js server, defining routes, and fetching the student data. This application uses Express.js to listen for requests and provide responses. In this case, the server would fetch student information (potentially from a database, but for simplicity, let's assume it is mock data). Once the data is retrieved, it is passed to the EJS template engine, which renders the HTML with the student's name and ID populated into the appropriate placeholders from the template. The rendered HTML is then sent as a response to the client's browser.

To facilitate project management, we utilize a package.json file. This file, created using the command npm init -y, acts as a central repository for metadata, including project dependencies (libraries the application relies on), scripts for common tasks, and the application's version number. The package.json file lists all the necessary libraries required by the project, including Express.js and EJS. After creating package.json, the dependencies are installed using npm install. This command downloads and installs the packages listed in package.json into a local node_modules directory.

After setting up the project and installing the required dependencies, the application needs to be configured to use EJS as the templating engine. This is generally achieved by setting up a view engine within the Express.js application. This step usually involves telling Express.js where to find the template files (the views directory in our example) and specifying EJS as the engine to be used for rendering templates.

Once everything is configured, the application can be started. This involves navigating to the project directory using the command prompt and running the command node index.js (or similar, depending on your file naming). The application will then start listening on a specified port (e.g., localhost:3005), ready to handle incoming requests. When a request is made to the server (e.g., by navigating to http://localhost:3005 in a web browser), the application’s server-side code will be executed. It will fetch the necessary data (in our case student information), and this data will be passed to the EJS template for rendering. The resulting HTML will then be sent to the user's browser, displaying the student information.

In summary, EJS provides a clean and efficient way to create dynamic web pages in Node.js and Express.js applications. By separating the presentation logic (HTML) from the application logic (JavaScript), EJS promotes code organization and maintainability. Its simple syntax and integration with Express.js make it a popular choice for many web developers. The ability to dynamically generate HTML based on server-side data allows for highly personalized and responsive web applications. This tutorial showcases a basic implementation, and the real-world applications of EJS extend far beyond this simple example, enabling the creation of much more complex and feature-rich web applications.

Read more

More from this blog

The Engineering Orbit

1174 posts

The Engineering Orbit shares expert insights, tutorials, and articles on the latest in engineering and tech to empower professionals and enthusiasts in their journey towards innovation.