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');
const app = express();
app.use('/', (req, res, next) => {
res.render('index.pug', { name: 'John Doe', age: 21 });
});
app.listen(5000, () => {
console.log('App listening on port 5000');
});
Explanation: The above code it split into 3 sections:
Importing express and initializing its instance
Creating a route that will serve the HTML template and also pass data into it (name and age of a user).
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
Learn to code easily with our course
Coding for Everyone . This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
07 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...