By Passing Data Object
Passing parameters via data object involves creating an object containing the parameters and passing it to the included template’s render function. In the main EJS template, you use <%- include(‘included_template.ejs’, data) %> to include the template and pass the data object. Then, in the included template, you can access the parameters using EJS syntax, such as <%= param1 %>.
HTML
<!-- main.ejs --> <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Main Template</ title > </ head > < body > < h1 >Main Template</ h1 > <%- include('included_template.ejs', data) %> </ body > </ html > |
Javascript
//server.js const express = require( 'express' ); const ejs = require( 'ejs' ); const app = express(); app.set( 'view engine' , 'ejs' ); app.get( '/' , (req, res) => { const data = { param1: 'hello' , param2: 'geek' }; res.render( 'main' , { data: data }); }); app.listen(3000, () => { console.log( 'Server is running on port 3000' ); }); |
Output:
How to include a template with parameters in EJS ?
EJS (Embedded JavaScript) is a templating language that enables dynamic content generation in HTML files using JavaScript syntax. EJS templates consist of HTML code mixed with JavaScript expressions enclosed within <% %> tags.
We will discuss the following approaches to include template with parameters in EJS
Table of Content
- Using Custom Functions
- Using Global Variables
- By Passing Data Object
- By Passing Parameters Directly