June 26, 2024

ExpressJS Template Engines Introduction

For creating view part of Express.js web app you can use HTML but that doesn't give you that much flexibility to create dynamic content. In order to make your HTML dynamic you can use template engines like Pug, EJS, Mustache. These template engines take the template as input and transform it into an HTML file at runtime by replacing variables in a template file with actual values.

ExpressJS Template Engines

Settings in Express.js for rendering templates

In the app.js or index.js which are the conventional names for the entry point of your Express app you need to set the following application setting properties for the template engine you are using.

1. You need to set the location of the directory where the template files are saved. For that 'views' property is used.

app.set('views', './views')

Above setting sets the views directory in the application root directory as the location where template files are saved. Template engine will search this directory to locate the template that has to be transformed.

2. As already mentioned, there are many template engines available so you need to install the one you are going to use and also set it in your Express app by using the property named 'view engine'.

app.set('view engine', 'pug')

Above setting sets pug as the template engine.

How to render template in Express.js

Steps for using template engine and getting the end HTML file which is sent to the client are as given below.

  1. Install the template engine you want to use.
    For example, if you are going to use pug as template engine.
    npm install pug -save
  2. Set the properties as mentioned above to configure the template engine in the Express app.
  3. For transforming and sending the resultant HTML to the client you can use res.render() method.
    res.render(view, locals, callback)
    • view- File path of the template to render.
    • locals- An object whose properties define values for local variables to be replaced in the view template. This is an optional parameter.
    • callback- A callback function. Function takes two parameters (err, html) where err encapsulates the error, if any and html stores the rendered HTML as string. This is an optional parameter.

Pug Template Example

Here is a simple example to show how to use pug template engine.


doctype html
        meta(name="viewport", content="width=device-width, initial-scale=1.0")
        title #{pageTitle}
        h3(align='center') A pug template
        p= message

There are 2 variables in the template pageTitle and message. You can either use #{} for a variable or equal sign (=).


const express = require('express');

const app = express();

const port = 3000;
const path = require('path');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.get('/', (req, res) => {
    res.render('home', {pageTitle: 'MyPage', 
    message: 'Hello From Pug Template Engine'});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)

You can see the properties that are set for template engine. In res.render() method template name is passed as the first parameter and as a second parameter values are set for the variables in the template.

Once you run the app and access URL- http://localhost:3000/

Pug with Express.js

If you view the page source you can see the rendered HTML.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <h3 align="center">A pug template</h3>
    <p>Hello From Pug Template Engine</p>

That's all for the topic ExpressJS Template Engines Introduction. If something is missing or you have something to share about the topic please write a comment.

You may also like

No comments:

Post a Comment