In web development, sending data from .ejs files (which are Embedded JavaScript templates) to .js files (typically server-side JavaScript files or client-side JavaScript scripts) usually involves several steps. However, it is important to note that in most cases, data is passed from .js files to .ejs files, not the other way around. Here, we distinguish between two scenarios: one involving server-side usage with Node.js and Express, and the other involving client-side processing.
Server-side: Node.js + Express
In this scenario, .ejs files serve as template files for generating HTML, while .js files typically refer to server-side scripts, such as Express route handlers. In this case, data is typically passed from .js files to .ejs files, not the other way around. Here is a common example:
-
Setting up Express and EJS First, you need to install and configure Express and EJS in your Node.js project.
javascriptconst express = require('express'); const app = express(); // Set EJS as the view engine app.set('view engine', 'ejs'); // Set the views directory app.set('views', path.join(__dirname, '/views')); -
Route Handling In Express route files, you can pass data to the .ejs template for rendering.
javascriptapp.get('/', (req, res) => { const data = { message: "Hello from server" }; res.render('index', data); });Here, the
dataobject contains the data to be passed to theindex.ejstemplate. -
Using Data in EJS Template In the
index.ejsfile, you can use<%= message %>to display data passed from the .js file.html<!DOCTYPE html> <html> <head> <title>My Page</title> </head> <body> <h1><%= message %></h1> </body> </html>
Client-side
If you want to send data from the HTML generated by client-side .ejs files to client-side .js files, the common approach is to embed data within the HTML and then read it in the .js file.
-
Embedding Data in HTML In
index.ejs, you can embed data into HTML elements' data attributes or define global variables within<script>tags.html<div data-message="<%= message %>"></div> <script> var messageFromServer = "<%= message %>"; </script> -
Reading Data in JavaScript In client-side .js files, you can retrieve this data by querying DOM elements' data attributes or using global variables.
javascript// Using data attributes const message = document.querySelector('div').dataset.message; // Using global variables console.log(messageFromServer);
Summary: Typically, data is sent from .js files to .ejs files, especially in server-side rendering scenarios. For client-side processing, data is usually passed through HTML.