What Is PUG Javascript Template Engine? : Beginners Guide.

Pug, formerly known as Jade, is a high-performance JavaScript Template Engine that simplifies HTML generation. Influenced by Haml, Pug offers a concise and elegant syntax that enhances code readability and maintainability. Seamlessly integrated with Node.js and browsers, Pug empowers developers to create dynamic and responsive web applications.

[the_ad id=”2256″]

if you are new to Node js read our previous post: How To Create Node.js Apps On Android? : Termux.

What Is Template Engine?

Template engines, also known as template processors, are versatile tools that facilitate the creation of documents by combining templates with structured data. They are widely employed for generating bulk emails, streamlining source code preprocessing, and crafting dynamic HTML pages.

Template engines allow us to structure dynamic content into reusable templates, which are later populated with data during the rendering process.

How To Install Pug.js?

Before installing Pug.js, you need to make sure you have Node.js and NPM installed on your system. You can download and install Node.js from its official website: https://nodejs.org/en/download

Install Node.js on Android in Termux.

You can install Pug.js using npm, run following command in empty directory(Recommended).

npm init -y
npm install pug

Or install Pug.js globally using following command.

npm install pug -g

Installing Pug.js globally makes it available to use from any directory.

Render Pug.js From String.

const pug = require('pug')

const template = 'p #{name} is a #{occupation}';

const data = { 'name': 'Viliyam Vasava', 'occupation': 'Programmer and Blogger.' };

const output = pug.render(template, data);

console.log(output);

Output:

pug template engine

Code Explanation

const pug = require('pug'); // Import the Pug library;

This line of code imports the Pug library into the current JavaScript file. This library provides the functionality for rendering Pug templates.

const template = 'p #{name} is a #{occupation}'; // Define the Pug template;

This line of code defines a Pug template string. The template string is a combination of static HTML and dynamic placeholders. The placeholders are represented by #{} expressions, which will be replaced with data values during the rendering process.

const data = { 'name': 'Viliyam Vasava', 'occupation': 'Programmer and Blogger.' }; // Create the data object;

This line of code creates a JavaScript object that contains the data values to be used for rendering the template. The object has two properties: name and occupation, which correspond to the placeholders in the template.

const output = pug.render(template, data); // Render the template;

This line of code renders the Pug template using the provided data object. The render() function takes the template string and the data object as arguments and returns the rendered HTML output.

console.log(output); // Display the output

This line of code prints the rendered HTML output to the console. The output will be the following HTML:

<p>Viliyam Vasava is a Programmer and Blogger.</p>

This demonstrates how Pug can be used to generate dynamic HTML content from a template and data object.

Create And Use Pug.js Template File.

const http = require('http');
const pug = require('pug');
const fs = require('fs');

const server = http.createServer((req, res) => {
  const template = fs.readFileSync('template.pug','utf-8');
  const data = {name: 'Viliyam Vasava'};
  const html = pug.render(template, data);
  
  res.writeHead(200,{'Content-Type': 'text/html'})
  res.end(html);
});

server.listen(3000,()=>{
  console.log("Serevr listening at: http://localhost:3000");
});


The first three lines imports three modules: http, pug, and fs.

  • The http module is used to create an HTTP server that can handle incoming requests and send responses.
  • The pug module is a template engine used to generate HTML content from templates.
  • The fs module is used to read and write files.

Here is a breakdown of main code:

Creating an HTTP Server:

const server = http.createServer((req, res) => {

})

This line creates an HTTP server using the http module and assigns it to the variable server. The provided callback function is executed for each incoming request.

Reading Template File:

const template = fs.readFileSync('template.pug', 'utf-8');

: This line reads the contents of the file named template.pug using the fs module and assigns it to the variable template. The utf-8 encoding ensures the file is read correctly.

Preparing Data for Rendering:

const data = { name: 'Viliyam Vasava' };

: This line creates a JavaScript object named data and assigns it a property named name with the value 'Viliyam Vasava'. This data will be used to populate the template.

Rendering the Pug Template:

const html = pug.render(template, data)

: This line renders the Pug template using the pug module. It takes the template string and the data object as parameters and generates an HTML string. The resulting HTML string is stored in the html variable.

Setting Response Headers:

res.writeHead(200, { 'Content-Type': 'text/html' });

: This line sets the HTTP response headers. It specifies a status code of 200 (indicating success) and sets the Content-Type header to text/html, indicating that the response is an HTML document.

Sending the Response:

res.end(html);

 This line sends the generated HTML content (html) to the client as the response body. The response is then terminated.

The server.listen() method is used to start the HTTP server. The first argument to the listen() method is the port number on which the server should listen for incoming requests. In this case, the server will listen on port 3000.

The second part of the code snippet is a callback function that is executed once the server has successfully started. The callback function logs a message to the console indicating that the server is listening on port 3000.

Check out official documentation of PUG here

[the_ad id=”2256″]

Discover more from Easymux

Subscribe now to keep reading and get access to the full archive.

Continue reading