Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Express.js Template Engines

Template engines in Express.js allow 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. This guide covers key concepts, examples, and best practices for using template engines in Express.js.

Key Concepts of Template Engines

  • Template Engine: A library that enables you to use static template files and inject data into them.
  • View Engine: The specific template engine used in an Express.js application, set via app.set('view engine', 'engine').
  • Views Directory: The directory where your template files are located, set via app.set('views', 'path/to/views').

Installing and Setting Up a Template Engine

To use a template engine, you first need to install it via npm. Here, we'll use Pug (formerly Jade) as an example:

Example: Setting Up Pug

mkdir my-express-app
cd my-express-app
npm init -y
npm install express pug --save

Create a basic Express server and configure it to use Pug as the template engine:

// app.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

// Set Pug as the template engine
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));

// Define routes
app.get('/', (req, res) => {
    res.render('index', { title: 'Home', message: 'Hello, World!' });
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Create a views directory and add a Pug template file:

// views/index.pug
doctype html
html
    head
        title= title
    body
        h1= message

Using Template Engines

You can use various template engines with Express.js. Here are examples of using Pug, EJS, and Handlebars:

Example: Using EJS

npm install ejs --save

// app.js
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;

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

// Define routes
app.get('/', (req, res) => {
    res.render('index', { title: 'Home', message: 'Hello, World!' });
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});
// views/index.ejs



    <%= title %>


    

<%= message %>