Horje
How to create helper functions with EJS in Express ?

Helper functions in EJS are JavaScrict functions that you can define and use within your templates. These functions can perform various tasks, such as formatting dates, generating dynamic content, or handling repetitive logic. By creating helper functions, you can keep your template code clean and organized, making it easier to maintain and understand.

In this article, we will explore how to create helper functions with EJS in Express.

Steps to create helper functions with EJS in Express:

Step 1: Initialize the node application using the following command.

npm init -y

Step 2: Install the required dependencies:

npm install express ejs nodemon

Folder Structure:

wqertgh

The updated dependencies in package.json file will look like:

"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.3"
}

Example: Now create the required files as shown in folder structure and add the following codes.

HTML

<!-- views/index.js -->
 
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Formatting date</title>
</head>
 
<body>
    <h1>
        <%= message %>
    </h1>
    <p>Today's date is: <%= formatDate(new Date()) %>
    </p>
</body>
 
</html>

Javascript

//app.js
 
const express = require('express');
const app = express();
const port = 3000;
 
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
 
app.get('/', (req, res) => {
    res.render('index',
        { message: 'Formatting date using helper function in ejs' });
});
 
app.locals.formatDate = (date) => {
    if (!date || !(date instanceof Date)) return '';
 
    const options = {
        year: 'numeric',
        month: 'long', day: 'numeric'
    };
    return date.toLocaleDateString('en-US', options);
};
 
app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});

To start the application run the following command

nodemon app.js

Output:

Screenshot-from-2024-02-25-21-28-55

Formatting date using helper function in ejs




Reffered: https://www.geeksforgeeks.org


Node.js

Related
How to Resolve Error: Cannot find module &#039;ejs&#039; ? How to Resolve Error: Cannot find module &#039;ejs&#039; ?
How to include a template with parameters in EJS ? How to include a template with parameters in EJS ?
What is EJS Template Engine ? What is EJS Template Engine ?
Filters in Pug View Engine Filters in Pug View Engine
How to check for undefined property in EJS for Node.js ? How to check for undefined property in EJS for Node.js ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13