Node.js Express Template Engines

Tags: Node.js Express Template Engine Ejs Pug

Node.js Express template engine

Node.js Express Template Engines allows you to use static template files in your application. At runtime, the template engine takes variables from a template file and replaces the actual values, and converts the template into an HTML file and sends it to the client. This approach makes it easy to design an HTML page.

Some popular template engine that work with Express: Pug, Mustache, and EJS. Express application generator uses Jade by default, but also supports others.

Developed web pages are generally in a similar structure. Only some sections on the page differ.

For example; On the articles page on this site, only the article title and content of the article change, the bottom and top of the site remain the same on each page.

The set method view engine value is used to add the template engine to the project developed with Express.

app.set('view engine', 'view-engine');

Express templates are set to the views folder in the same folder by default.

The set method views value is used to change the template path.

app.set('views', 'template-path');

Express module supports various JavaScript template engines and enables template engine creation.

The use of supported template engines varies.

When choosing a template engine, conditions such as the usage of the template engine, ease of use and the possibility to use JavaScript commands within the template are taken into account.

Supports Express Pug, Mustache, EJS, Dust, Handlebars, nunjucks .etc template engines.

Including the template engine in the project

To include the selected template engine in the project, first the package of the template engine is downloaded via NPM.

npm install pug --save

After downloading the template engine, the necessary settings are made.

'use strict';
const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.set('views', './view');
app.listen(8000, function () {
    console.log('Server running...');
});

After the necessary settings are made, the express template becomes ready to convert to HTML and waits for the file to be translated.

Save the following codes as index.pug in the view set as template folder.

    
html
head
    meta(charset="UTF-8")
    title Hello Sir Node
body
    h1 Hi Pug

With Express, the rendering method in the Express module is used to convert a file to HTML with the template engine.


'use strict';

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

app.set('view engine', 'pug');
app.set('views', './view');

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

app.listen(8000, function () {
  console.log('Server running...');
});

When connected to the web server, it will run the express pug template engine and convert the index.pug file in the view folder to HTML.

The object parameter is passed to the second parameter of the render method to send the value into the template file.


'use strict';

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

app.set('view engine', 'pug');
app.set('views', './view');

app.get('/', function (req, res) {

  res.render('index', {
    title: 'Hello Pug and Express'
  });

});

app.listen(8000, function () {
  console.log('Server is running.');
});

The values in the object parameter are used in the template file as follows.


html
head
    meta(charset="UTF-8")
    title=title
body
    h1=title

There can be more than one different value such as an object or array in the object sent as a parameter.


'use strict';

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

app.set('view engine', 'pug');
app.set('views', './view');

app.get('/', function (req, res) {

  res.render('index', {
    title: 'Hello Pug and Express',
    name: 'Sir',
    surname: 'Node'
  });

});

app.listen(8000, function () {
  console.log('Server is running...');
});

Multiple values can be used as follows.


    html
    head
        meta(charset="UTF-8")
        title=title
    body
        h1=title
        p Hello my name is #{name} 
        p surname is #[strong #{surname}]

The most important feature of template engines is that they allow JavaScript commands to be used within the template.


html
head
    meta(charset="UTF-8")
    title=title
body
    h1=title
    ul 
        -for (let count = 1; count <= 10; ++count )
            li #{count} Hello

Gaps need to be taken care of when using the Pug template engine otherwise it may give unexpected results.

Using the EJS template engine

The EJS template engine can be used as an alternative to the Pug template engine.

For the EJS template engine to be included in the project, the package of the template engine is first downloaded via NPM.

npm install ejs --save

After the template engine is downloaded, the necessary settings are made as in the Pug template engine, and the EJS files are converted to HTML with the render method.


        'use strict';

        const express = require('express');
        const app = express();
        
        app.set('view engine', 'ejs');
        app.set('views', './view');
        
        app.get("/", function (req, res) {
        
          res.render('index', {
            title: 'Hello EJS and Express',
            name: 'Sir',
            surname: 'Node'
          });
        
        });
        
        app.listen(8000, function () {
          console.log('Server is running...');
        });

Save the following codes as index.ejs in view folder set as template folder and run it.


    <!DOCTYPE html>
        <html>
        <head>
        <meta charset="UTF-8" />
        <title><%=title%></title>
        </head>
        <body>
        <h1><%=title%></h1>
        <p>Hello öy name is <%=name%></p>
        <p>surname <strong><%=surname%></strong></p>
        </body>
        </html>

Within the EJS, JavaScript commands are written<% here%>.

Save the following codes as index.ejs in view folder set as template folder and run it.

<!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title><%=title%></title>
    </head>
    <body>
    <ul>
    <% for (let count = 1; count <= 10; ++count ) { %>
    <li><%=count%> Hello</li>
    <% } %>
    </ul>
    </body>
    </html>

Usage of template engines is generally the same.

However, the features used may differ depending on the template engines.

As a result, in this article we learned Node.js Express Template Engines. If you want to learn more, keep in touch with sirnode. We advice you to read Routing Operations in Express.js that teachs route management and how to dynamically routing in express.