How to Pass Data to Components in EJS & NodeJS

By onjsdev

Jan 6th, 2024

In EJS (Embedded JavaScript), you can pass data to components by using the <%- include(filename, locals) %> syntax. The filename is the path to the EJS file you want to include, and locals is an object containing the data you want to pass to that file.

Here's an example of how you can pass data to a component in EJS:

Assuming you have a file named main.ejs:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My EJS Example</title>
    <h1>Main Page</h1>
    <% var dataToPass = { message: "Hello from main.ejs" }; %>
    <%- include('component.ejs', dataToPass) %>

And a file named component.ejs:

    <p><%= message %></p>

In this example, we define an object dataToPass in the main.ejs file and include the component.ejs file using <%- include('component.ejs', dataToPass) %>. The dataToPass object is then accessible in the component.ejs file, and we can use <%= message %> to display the value of the message property.

Make sure to adjust the file paths according to your project structure. This is a simple example, and you can pass more complex data structures as needed for your application.

You can check the following articles:

Thank you for reading