0
0
Expressframework~5 mins

Template engine concept in Express

Choose your learning style9 modes available
Introduction

A template engine helps you create HTML pages by mixing static content with dynamic data easily.

You want to show user-specific information on a webpage, like a username.
You need to generate HTML pages that change based on data from a database.
You want to separate your webpage design from your server code for easier updates.
You want to reuse parts of your webpage like headers or footers across many pages.
Syntax
Express
res.render('templateName', { key: value, ... });
The 'templateName' is the file without extension in your views folder.
The object passed contains data you want to show in the template.
Examples
This sends data to the 'home' template to show a title and user name.
Express
res.render('home', { title: 'Welcome', user: 'Alice' });
This renders the 'profile' template with age and city data.
Express
res.render('profile', { age: 30, city: 'Paris' });
Sample Program

This Express app uses EJS as the template engine. When you visit the homepage, it sends the message 'Hello, friend!' to the 'index' template, which shows it inside an <h1> tag.

Express
import express from 'express';
import path from 'path';

const app = express();

// Set EJS as the template engine
app.set('view engine', 'ejs');
app.set('views', path.join(process.cwd(), 'views'));

app.get('/', (req, res) => {
  res.render('index', { message: 'Hello, friend!' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

// views/index.ejs content:
// <html>
// <head><title>Home</title></head>
// <body>
//   <h1><%= message %></h1>
// </body>
// </html>
OutputSuccess
Important Notes

Make sure to install the template engine package (like ejs) with npm before using it.

Templates help keep your HTML clean and easy to update without changing server code.

Summary

Template engines mix HTML with data to create dynamic pages.

Use res.render() in Express to send data to templates.

Templates keep your design and code separate for easier maintenance.