Open In App

How to print a variable directly using EJS template engine?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

EJS (Embedded JavaScript) is a templating engine for NodeJS that enables dynamic content generation in web applications. To print a variable directly in an EJS template, you can use the <%= variable %> syntax. This syntax allows you to embed and display the value of a variable directly within the HTML content of the template. In this article, we will explore the detailed practical demonstration to print a variable directly using the EJS template engine.

Steps to print a variable directly using the EJS template engine:

Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.

mkdir root
cd root

Step 2: Once the folder is been created, we will initialize NPM using the below command, this will give us the package.json file.

npm init -y

Step 3: Once the project is been initialized, we need to install Express and EJS dependencies in our project by using the below installation command of NPM.

npm i express ejs

Project Structure:

PS

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

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

Example: Below is an example of printing a variable directly using EJS template engine.

HTML




<!DOCTYPE html>
<head>
    <title>EJS Example</title>
</head>
<body>
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h3>Print Variable Directly</h3>
    <form action="/greet" method="post">
        <label for="name">Enter your name:</label>
        <input type="text" id="name" name="name" required>
        <button type="submit">Submit</button>
    </form>
    <% if (greeting) { %>
        <p><%= greeting %></p>
    <% } %>
</body>
</html>


Javascript




const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
    res.render('index', { greeting: '' });
});
app.post('/greet', (req, res) => {
    const name = req.body.name;
    const greeting = `Hello, ${name}!`;
    res.render('index', { greeting });
});
app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});


To run the application, we need to start the server by using the below command.

node server.js

Output:

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads