setup ejs views directory in express

To set up EJS views directory in Express, follow these steps:

  1. Install EJS: Start by installing EJS as a dependency in your project. You can do this by running the following command in your terminal:
npm install ejs
  1. Create a views directory: Inside your project's root directory, create a new directory called "views." This is where you will store your EJS templates.

  2. Configure Express to use EJS: In your Express application file (usually app.js or index.js), require the 'ejs' module and set EJS as your view engine. This can be done using the following code:

const express = require('express');
const app = express();

app.set('view engine', 'ejs');
  1. Specify the views directory: To tell Express where to find your EJS templates, use the app.set method with the 'views' property. Provide the path to your views directory as the value. In this case, it is the 'views' directory you created earlier. Add the following code after setting the view engine:
app.set('views', path.join(__dirname, 'views'));
  1. Create EJS templates: Inside the 'views' directory, create your EJS templates with a .ejs file extension. These templates will be used to render dynamic content.

  2. Render EJS templates: Finally, to render an EJS template, use the res.render method in your route handler. Specify the name of the EJS template file (without the file extension) as the argument. For example:

app.get('/', (req, res) => {
  res.render('index');
});

That's it! You have successfully set up the EJS views directory in your Express application.