Template Engines (EJS)

A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client.

1. Installation & Setup

npm install ejs

In your app.js:

app.set('view engine', 'ejs');
app.set('views', './views'); // Default folder

2. Creating a Template (index.ejs)

EJS files use .ejs extension and look exactly like HTML, but with brackets <% %>.

<html>
  <body>
    <h1>Welcome, <%= userName %>!</h1>
    <ul>
      <% items.forEach(item => { %>
        <li><%= item %></li>
      <% }); %>
    </ul>
  </body>
</html>

3. Rendering the View

app.get('/', (req, res) => {
  res.render('index', {
    userName: 'Pradeep',
    items: ['Learn Express', 'Build App', 'Deploy']
  });
});
Pug vs EJS: EJS uses vanilla HTML/JS syntax, making it easier for many. Pug uses indentation-based syntax which is cleaner but has a steeper learning curve.