Open In App

How to pass/access node.js variable to an html file/template ?

Improve
Improve
Like Article
Like
Save
Share
Report

The following approach covers how to pass/access node.js variable to an HTML file/template. We will build a basic Node.js application that will let you show dynamic content on an HTML page, i.e. your name and age. For adding the name and age values to our HTML template, we’ll be using the pug package. 

Pug is a template engine that can be used to inject dynamic data into an HTML page. Its function is to convert the provided data into HTML content and serve it as a static page. Pug’s syntax resembles that of traditional HTML but is a lot cleaner and prioritizes indentation and spacing for controlling the flow of logic. 

Creating NodeJS Application And Installing Module:

  • Step 1: We can create a new project with Node Package Manager by using the following command.

    npm init
  • Step 2: Install the required project dependencies i.e express and pug modules using the following command.

    npm install express pug --save

By default, all HTML templates are stored in the views folder in a project. We’ll create the template file index.pug using the same structure.

Project Directory: Our project directory will look like this.

Project Structure

index.js




const express = require('express');
  
// Initialize App
const app = express();
  
// Assign route
app.use('/', (req, res, next) => {
  res.render('index.pug', { name: 'John Doe', age: 21 });
});
  
// Start server
app.listen(5000, () => {
  console.log('App listening on port 5000');
});


Explanation: The above code it split into 3 sections:

  1. Importing express and initializing its instance
  2. Creating a route that will serve the HTML template and also pass data into it (name and age of a user).
  3. Starting the server.

index.pug




doctype html
html(lang="en")
  head
    title= 'Node.js Template'
  body
    h1 My name is #{name}
    p I am #{age} years old


Explanation: Behind the scenes, the above pub code along with the provided data is translated into an HTML page and then served via the Node.js application.

Step to run the application:

Run the index.js file using the following command.

node index.js

Output: Now open your browser and go to http://localhost:5000/, you will see the following output:

Visual Representation of index.pug template



Last Updated : 07 Apr, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads